﻿// RMSServerDlg.cpp : implementation file
//
#include "stdafx.h"
#include "afx.h"
#include "RMSServer.h"
#include "RMSServerDlg.h"
#include "RMSClientID.h"
#include "SetBitrateDlg.h"
#include "SetServerDlg.h"
#include "SetFrameRateDlg.h"
#include "PasswordDlg.h"

#include "../Capture/CapLib.h"
#include "InCall.h"

#include "../GUI/Messages.h"

#include "../Common/CTags.h"

#include "../RMSTomline/AuthServer/log.h" // debugg

#include "Mmsystem.h"
#include <io.h>
#include <errno.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define IDC_PREVIEW			11222
#define ID_DRAWER_PREF		100
#define IDC_VIDEO			101
#define IDC_AUDIO			102
#define IDC_SLEEP			103
#define IDC_CLIENT_LIST		104
#define IDC_START_VIEWER	105

#define IDC_CAST			106
#define IDC_CONF			107

#define IDC_HI	     		406
#define IDC_LOW	 	     	407

#define IDC_VIDEOSOURCE     108
#define IDC_SETPARAMETERS   109
#define IDC_EXITBUTTON		110
#define IDC_WINDOWMIN	    111
#define IDC_ICON			112

#ifdef _GUI2008_
  #define IDM_SETTINGS 300
  #define IDM_SETPARAMETERS 301
  #define IDM_CAST 302
  #define IDM_CONF 303
  #define IDM_VIDEOSOURCE 304
  #define IDM_STARTVIEWER 305
  #define IDM_ENABLESETTINGS 306
#endif


#define ENCODER_REGISTRY_KEY	_T("Software\\Streambox Everywhere\\Settings\\Encoder")
#define ENCODER_MUTEX_NAME		_T("NetVC Encoder Mutex")

#ifdef _NET_VC_
	#include "../GUI/WinPlace.h"

#ifdef _GUI2008_
	//@Comment by TOMOKOH
	//  SKIN_BITMAP ‚ÍˆÈ‰º‚Ì@dlgéŒ¾‚Å‰Šú‰»‚³‚ê‚é
	//	CRMSServerApp::InitInstance() “à‚Ì301s•t‹ß‚Ì’è‹`
	//		CRMSServerDlg dlg;
	//  gUserModeEnabled(true/false) ‚Ì’l‚ðSKIN_BITMAP‚Ì’l‚É‘«‚µ‚ÄƒŠƒ\[ƒX‚ð“Ç‚Ýž‚Þ‚Ì‚Å
	//  Žw’è‚·‚éƒŠƒ\[ƒX’l‚Í@ƒ†[ƒU[ƒ‚[ƒhAadminƒ‚[ƒh‚ª˜A”Ô‚Æ‚È‚Á‚ÄŽw’è‚·‚éŽ–
	//  —áj@
	//		#define IDB_SKIN_SINGLE_JP              268 ---@admin ƒ‚[ƒhŽž‚ÌƒCƒ[ƒW
	//		#define IDB_SKIN_SINGLE_JP2             269 --- ƒ†[ƒU[ƒ‚[ƒhŽž‚ÌƒCƒ[ƒW
	//
	//  Bitmap‰Šú‰»
	//@@@CRMSServerDlg::CRMSServerDlg(CWnd* pParent@/*=NULL*/)
	//@@@: CMegaDialog(CRMSServerDlg::IDD, pParent, SKIN_BITMAP+(int)gUserModeEnabled, SKIN_BITMAP+(int)gUserModeEnabled)
	//


  #ifdef _J707_ //#J7070001-TOMOKOH
	#define SKIN_BITMAP			IDB_SKIN_SINGLE_JP
  #else
	#define SKIN_BITMAP			IDB_SKIN_SINGLE_2
  #endif 
#else
    #define SKIN_BITMAP			IDB_SKIN_SINGLE_1
#endif
	#define CMegaDialog			CMegaDialogNvc

	#define MIN_TIMER_EVENT_ID	10
#else //def _NET_VC_
	#define SKIN_BITMAP			IDB_SKIN_SINGLE
#endif //def _NET_VC_

HANDLE g_hNoVideoEnabled = NULL;

int STREAM_BOX_MESSAGE;

bool DisableFEC=false;
extern int EnableFEC;
extern int FECparam1;
extern int FECparam2;
extern unsigned int bindIP;

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

extern void* MainDlgPtr;
CRMSServerDlg* GetMainDlg()
{
  if(MainDlgPtr==0) return (CRMSServerDlg*)AfxGetMainWnd(); else return (CRMSServerDlg*) MainDlgPtr;
}
///#define GET_SERVER_DLG    (GetMainDlg())

//#define GET_SERVER_DLG    ((CRMSServerDlg*)AfxGetMainWnd())
#ifdef _OEM_
	#ifdef _TEC_	
		#define IDD1			IDD_ABOUTBOXTEC
	#else
		#define IDD1			IDD_ABOUTBOXQFI
	#endif
#else
	#ifdef _VC_J7_	
		#define IDD1			IDD_ABOUTBOXTEC
	#else
		#define IDD1			IDD_ABOUTBOX
	#endif
#endif


// move include log.h to 20 line in this file. Because compile error occures. "log.h" included at that position in 2009/12/28 build.
//#include "../RMSTomline/AuthServer/log.h" // debugg
extern CLog* pLog;


const int
  presetBitsHi = 100,
  presetFpsHi = 10,

  presetBitsLow = 10, // 18
  presetFpsLow = 1;

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD1 };
	CButtonST	m_btnSbLogo;		// streambox logo or powered by streambox
#ifdef _OEM_
	CButtonST	m_btnOemLogo;		// Oem logo
#endif
#ifdef _VC_J7_
	CButtonST	m_btnOemLogo;		// Oem logo
#endif

	CString	m_AboutInfo;
	CString	m_Build;
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	virtual BOOL OnInitDialog();
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	m_AboutInfo ="";
#ifdef EXPIRED
m_AboutInfo="This version will expire on Dec-1/2002\r\n";
#endif
#ifdef _OEM_
#ifndef _TEC_
m_AboutInfo="This version will expire on Apr-20/2003\r\n";
#endif
#endif

#ifdef _NET_VC_

#ifndef _VC_J7_
	m_AboutInfo+=_T("Streambox NetVC Encoder\r\n");
#else
  #ifdef _J707_ //#J7070004 / #J7070014
   #ifdef _J707_PROD_
	m_AboutInfo+=_T("QuantumFusion VC-J707 Encoder\r\n");
   #else
	m_AboutInfo+=_T("Wing Meeting Encoder\r\n");//QuantumFusion VC-J7 Encoder\r\n");
   #endif
  #else
	m_AboutInfo+=_T("Streambox VC-J7 Encoder\r\n");
  #endif
#endif

#elif defined VC70
	m_AboutInfo+=_T("Streambox VC-70 Encoder\r\n");
#else
	m_AboutInfo+=_T("Streambox VC-10 Encoder\r\n");
#endif

#ifdef _J707_ // #J7070006 / #J7070004 - TOMOKOH
	m_AboutInfo+=_T(""
//"(C) 1999-2010, QuantumFusion Inc.\r\n"
"All rights reserved.\r\n"
//"The Program and related user documentation,\r\n"
//"if any, are proprietary products of QuantumFusion Inc.,\r\n"
//"and are protected under U.S. and international\r\n"
//"copyright law. All right, title, and interest\r\n"
//"in and to the Program, including associated\r\n"
//"intellectual property rights, are and shall\r\n"
//"remain with QuantumFusion Inc.\r\n"
	);
#else
	m_AboutInfo+=_T(
"(C) 1999-2004, Streambox Inc.\r\n"
"All rights reserved.\r\n"
"The Program and related user documentation,\r\n"
"if any, are proprietary products of Streambox Inc.,\r\n"
"and are protected under U.S. and international\r\n"
"copyright law. All right, title, and interest\r\n"
"in and to the Program, including associated\r\n"
"intellectual property rights, are and shall\r\n"
"remain with Streambox Inc.\r\n"
	);
#endif
	m_Build=__DATE__;

	//}}AFX_DATA_INIT
}

BOOL CAboutDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	// Streambox logo button
	m_btnSbLogo.m_bShowDisabledBitmap = FALSE;
#ifdef _OEM_
	m_btnSbLogo.SetBitmaps(IDB_POWERED, RGB(192, 192, 192));
#else

#ifndef	_VC_J7_
	m_btnSbLogo.SetBitmaps(IDB_STREAMBOX, RGB(192, 192, 192));
#else
  #ifdef _J707_ //#J7070004 - TOMOKOH
	m_btnSbLogo.SetBitmaps(IDB_QFI_NONE, RGB(255, 0, 0));
#else
	m_btnSbLogo.SetBitmaps(IDB_POWERED, RGB(192, 192, 192));
  #endif
#endif

#endif
	m_btnSbLogo.SizeToContent();
	// OEM logo
#ifdef _OEM_
	m_btnOemLogo.m_bShowDisabledBitmap = FALSE;
#ifdef _QFI_
	m_btnOemLogo.SetBitmaps(IDB_QFI, RGB(255, 0, 0));
	GetDlgItem(IDC_OEM_STRING)->SetWindowText("OEM version for QuantumFusion Inc.");
#endif
#ifdef _VITAL_
	m_btnOemLogo.SetBitmaps(IDB_VITAL, RGB(255, 0, 0));
	GetDlgItem(IDC_OEM_STRING)->SetWindowText("OEM version for Vital USA");
#endif
#ifdef _TEC_
	m_btnOemLogo.SetBitmaps(IDB_JAEA_LOGO, RGB(255, 255, 255));
	GetDlgItem(IDC_OEM_STRING)->SetWindowText("OEM version for JAEA");
#endif

	m_btnOemLogo.SizeToContent();
	//
#endif
#ifdef _VC_J7_
	m_btnOemLogo.m_bShowDisabledBitmap = FALSE;
	m_btnOemLogo.SetBitmaps(IDB_JAEA_LOGO, RGB(255, 255, 255));
	GetDlgItem(IDC_OEM_STRING)->SetWindowText("OEM version.");
	m_btnOemLogo.SizeToContent();
#endif



#ifdef _NET_VC_

#ifndef _VC_J7_
	GetDlgItem(IDC_VER_INFO)->SetWindowText("Streambox NetVC Encoder. Version 1.2");
	SetWindowText("About Streambox NetVC Encoder");
#else
  #ifdef _GUI2008_
   #ifdef _J707_ //#J7070004 / #J7070014
     #ifdef _J707PROD_
	    GetDlgItem(IDC_VER_INFO)->SetWindowText("QuantumFusion VC-J707 Encoder. Version 1.2");
     #else
		GetDlgItem(IDC_VER_INFO)->SetWindowText("Wing Meeting Encoder. Version 1.0");
     #endif
   #else
		GetDlgItem(IDC_VER_INFO)->SetWindowText("Streambox VC-J7 Encoder. Version 1.2");
   #endif
  #else
	GetDlgItem(IDC_VER_INFO)->SetWindowText("Streambox VC-J7 Encoder. Version 1.2");
  #endif  
  #ifdef _J707_ //#J7070014
    #ifdef _J707PROD_
		SetWindowText("About QuantumFusion VC-J707 Encoder");
    #else
		SetWindowText("About Wing Meeting Encoder");
    #endif
  #else
		SetWindowText("About Streambox VC-J7 Encoder");
  #endif

#endif
	
#elif defined VC70
	GetDlgItem(IDC_VER_INFO)->SetWindowText("Streambox VC-70 Encoder. Version 1.2");
	SetWindowText("About Streambox VC-70 Encoder");
#else	
	GetDlgItem(IDC_VER_INFO)->SetWindowText("Streambox VC-10 Encoder. Version 1.2");
	SetWindowText("About Streambox VC-10 Encoder");
#endif

	return TRUE;  // return TRUE  unless you set the focus to a control

}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	DDX_Text(pDX, IDC_INFO, m_AboutInfo);
	m_Build="27-Feb-2015"; //Charith 27-05-2015
	DDX_Text(pDX, IDC_BUILD, m_Build);
	DDX_Control(pDX, IDC_LOGO, m_btnSbLogo); //Doerit 2015/02/26 ->Sachith
#ifdef _OEM_
	DDX_Control(pDX, IDC_OEM, m_btnOemLogo);
#endif
#ifdef _VC_J7_
	DDX_Control(pDX, IDC_OEM, m_btnOemLogo);
#endif
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRMSServerDlg dialog

// Global data
BYTE* pSleepBitmapData=0;// sleep Image
BYTE* pSleepBitmapDataCompressed=0;// sleep Image
int sizeSleepCompressed;

bool b640x480 = false;

int nFrameRate = 30;
int nCaptureBitrate = 0;
DWORD timeStart = 0;
DWORD timeEnd = 0;


bool bDisableCallback;

extern "C" {
extern double	LOGRUS_reqbitrate ; //default bitrate 1 Mbps
}

//	Format of stored video data
//	TAG: Stored
//	Time mark: year(DWORD), month(BYTE), day(BYTE), hour(BYTE), minute(BYTE), second(BYTE)
//	TAG: TIME size of Time: DWORD
//	TAG: DATE size of Date: DWORD
//	TAG: AUDIO size of Audio: DWORD
//	TAG: STOREDVIDEO size of STOREDVIDEO: DWORD

// copy data to internal buffer

extern CRMSServerApp theApp;

int _cdecl Process(void* data, int size, int nType)
{
	static DWORD dwDelta = 0;
	static int fps = 0;
	static long lTotalCaptureData = 0;
	CRMSServerDlg* dlg = (CRMSServerDlg*)AfxGetMainWnd();

_log("have = "<<size<<"/"<<nType<<"\n");
CRMSServerDlg* ppp = (CRMSServerDlg*)theApp.m_pMainWnd;
CRMSServerDlg* ppp2 = GET_SERVER_DLG;

	// copy video/audioo enable
 	BOOL   m_bVideo=ppp->m_bVideo;
	BOOL   m_bAudio=ppp->m_bAudio;

// 	BOOL   m_bVideo=GET_SERVER_DLG->m_bVideo;
	//BOOL   m_bAudio=GET_SERVER_DLG->m_bAudio;
		
	// disable actual data if 
	if (GET_SERVER_DLG->SleepMode) {
		m_bVideo=0;
		m_bAudio=0;
	}

	/*
	if(bDisableCallback)
	{
		return 0;
	}
	*/

	
	if (nType) {
			EnterCriticalSection(GET_SERVER_DLG->pCriticalData);

			GET_SERVER_DLG->m_time = CTime::GetCurrentTime();

			GET_SERVER_DLG->m_strTime = GET_SERVER_DLG->m_time.Format("%H:%M:%S");
			*GET_SERVER_DLG->pSzTime = GET_SERVER_DLG->m_strTime.GetLength()+1;
			strcpy((char*)(GET_SERVER_DLG->dtTime), static_cast<LPCTSTR>(GET_SERVER_DLG->m_strTime));

			GET_SERVER_DLG->m_strDate = GET_SERVER_DLG->m_time.Format("%B %d,%Y");
			*GET_SERVER_DLG->pSzDate = GET_SERVER_DLG->m_strDate.GetLength()+1;
			strcpy((char*)(GET_SERVER_DLG->dtDate), static_cast<LPCTSTR>(GET_SERVER_DLG->m_strDate));
			
			if(m_bVideo)
			{
				*GET_SERVER_DLG->pSzVideo=size;
				memcpy(GET_SERVER_DLG->dtVideo,data,size);
			} else
			{
				// send 1 frame per sec in Video-OFF mode
				DWORD dwtimeEnd = timeGetTime();
				DWORD dwdwDelta = dwDelta + (dwtimeEnd - timeStart);
				if(dwdwDelta > 1000)
				{
					// send sleep screen for V1
					if (*(GET_SERVER_DLG->BaseServer.GetDataPtr_TypeVideo(0)) == TAG_RMSVIDEO_v01) {
						*GET_SERVER_DLG->pSzVideo=size;
						memcpy(GET_SERVER_DLG->dtVideo,data,size);
					}
				}
			}
			timeEnd = timeGetTime();
			dwDelta = dwDelta + (timeEnd - timeStart);
			timeStart = timeGetTime();
			if(dwDelta > 1000)
			{
                _log("m_bVideo="<<m_bVideo<<"\n");
                if(m_bVideo)
                {
    			  nFrameRate = (int)((((float)fps * 1000.0) / (float)dwDelta) + .5);
			      nCaptureBitrate = (int)((((float)lTotalCaptureData * 8.0 / 1024.0) * 1000.0 ) / (float)dwDelta + .5);
                } else
                {
                  nFrameRate=0;
                  nCaptureBitrate=0;
                }
				fps = 0;
				dwDelta = 0;
				lTotalCaptureData = 0;
			}
			fps++;
			lTotalCaptureData += *GET_SERVER_DLG->pSzVideo; 
			LeaveCriticalSection(GET_SERVER_DLG->pCriticalData);
//			GET_SERVER_DLG->BaseServer.SendVideoEvent();
	}else{
		if(m_bAudio){
			EnterCriticalSection(GET_SERVER_DLG->pCriticalAudio);
			*GET_SERVER_DLG->pSzAudio=size;
			memcpy(GET_SERVER_DLG->dtAudio,data,size);
			lTotalCaptureData += *GET_SERVER_DLG->pSzAudio; 
			LeaveCriticalSection(GET_SERVER_DLG->pCriticalAudio);				
			GET_SERVER_DLG->BaseServer.SendWaveEvent();
		}else{
			// send dummy audio (all zeroz)
			//static BYTE empty[1024*10];
			size=33;
			EnterCriticalSection(GET_SERVER_DLG->pCriticalAudio);
			*GET_SERVER_DLG->pSzAudio=size;
			memcpy(GET_SERVER_DLG->dtAudio,AUDIO_SILENSE,size);
			lTotalCaptureData += *GET_SERVER_DLG->pSzAudio; 
			LeaveCriticalSection(GET_SERVER_DLG->pCriticalAudio);				
			GET_SERVER_DLG->BaseServer.SendWaveEvent();
		}
	}
	return 1;
}

CRMSServerDlg::CRMSServerDlg(CWnd* pParent /*=NULL*/)
	: CMegaDialog(CRMSServerDlg::IDD, pParent, SKIN_BITMAP+(int)gUserModeEnabled, SKIN_BITMAP+(int)gUserModeEnabled)
{
	m_bAudio = FALSE;
	m_bVideo = FALSE;

	//{{AFX_DATA_INIT(CRMSServerDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
#ifdef _J707_ //#J7070004
	OSVERSIONINFO osVersionInfo;
	ZeroMemory(&osVersionInfo, sizeof(OSVERSIONINFO));
    osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osVersionInfo);
	if (osVersionInfo.dwMajorVersion >= 6) // Windows Vista or later
	{
		m_hIcon = AfxGetApp()->LoadIcon(IDR_ICON_VIDEO); //Doerit 2015/02/26 ->Sachith
	}
	else
	{
		m_hIcon = AfxGetApp()->LoadIcon(IDR_ICON_VIDEO_XP); //Doerit 2015/02/26 ->Sachith
	}

#else
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
#endif

	// init data for One camera
	BaseServer.AllocateData(1);
	pSzVideo=BaseServer.GetDataPtr_SizeVideo(0);
	dtVideo=BaseServer.GetDataPtr_dtVideo(0);
	pSzDate=BaseServer.GetDataPtr_SizeDate(0);
	dtDate=BaseServer.GetDataPtr_dtDate(0);
	pSzTime=BaseServer.GetDataPtr_SizeTime(0);
	dtTime=BaseServer.GetDataPtr_dtTime(0);
	pCriticalData=BaseServer.GetDataPtr_CriticalData(0);
	pSzAudio=BaseServer.GetDataPtr_SizeAudio(0);
	dtAudio=BaseServer.GetDataPtr_dtAudio(0);
	pCriticalAudio=BaseServer.GetDataPtr_CriticalAudio(0);
	SleepMode=0;

	bWasSetStillImage = FALSE;

	STREAM_BOX_MESSAGE = RegisterWindowMessage("STREAM_BOX_MESSAGE_1");
		m_Dragable = FALSE; // 
#ifdef _NET_VC_
	m_hMutex = NULL;
	m_addr = _T("none");
#endif //def _NET_VC_
}

void CRMSServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CMegaDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CRMSServerDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CRMSServerDlg, CMegaDialog)
	//{{AFX_MSG_MAP(CRMSServerDlg)
	ON_COMMAND(IDC_WINDOWMIN, OnIDCMinimize) // charith 21/05/2015
	ON_WM_LBUTTONUP() // charith 21/05/2015
	ON_WM_LBUTTONDOWN() // charith 21/05/2015
	ON_WM_MOUSEMOVE()// charith 21/05/2015
	ON_WM_RBUTTONDOWN() // charith 25/05/2015
	ON_WM_NCRBUTTONDOWN()
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_SETSERVER, OnSetserver)
//	ON_BN_CLICKED(IDSAVE, OnSave)
	ON_BN_CLICKED(IDC_ICON, OnIconClick)

	ON_BN_CLICKED(IDC_AUDIO, OnSound)
	ON_BN_CLICKED(IDC_VIDEO, OnVideo)
#ifdef _GUI2008_
	ON_BN_CLICKED(IDC_HI, OnHi)
	ON_BN_CLICKED(IDC_LOW, OnLow)
#else
    ON_BN_CLICKED(IDC_CAST, OnCast)
	ON_BN_CLICKED(IDC_CONF, OnConf)
#endif

	ON_WM_CLOSE()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDCANCEL, OnExit)
	ON_BN_CLICKED(IDPASSWORD, OnPassword)
	ON_COMMAND(ID_HELP, OnHelp)
	ON_MESSAGE(IDC_INCALL,OnCall)
	ON_COMMAND(IDC_START_VIEWER, OnVC10)
	ON_LBN_SELCHANGE(IDC_CLIENT_LIST, OnSelchangeClients)
	ON_REGISTERED_MESSAGE(STREAM_BOX_MESSAGE,User_Message)

	ON_WM_ERASEBKGND()
	ON_MESSAGE(WM_SELECT_VIDEO_SOURCE, OnSelectVideoSource)
	ON_MESSAGE(WM_CHANGE_SERVER_PARAMS, OnChangeServerParams)
	ON_MESSAGE(WM_CHANGE_CYCLIC_BUFFER, OnChangeCyclicBuffer)
	ON_MESSAGE(WM_CHANGE_HOMEPATH, OnChangeHomePath)
	ON_MESSAGE(WM_CHANGE_PASSWORD, OnChangePassword)
	ON_MESSAGE(WM_CHANGE_BITRATE, OnChangeBitrate)
	ON_MESSAGE(WM_CHANGE_FPS, OnChangeFPS)
	ON_MESSAGE(WM_CHANGE_SIZE, OnChangeSize)

#ifdef _NET_VC_
	ON_BN_CLICKED(IDC_VIDEOSOURCE, OnVideoSource)
	ON_BN_CLICKED(IDC_SETPARAMETERS, OnSetParameters)
	ON_BN_CLICKED(IDC_CONF,OnSetParameters)

	ON_BN_CLICKED(IDM_VIDEOSOURCE, OnVideoSource)
	ON_BN_CLICKED(IDM_SETPARAMETERS, OnSetParameters)
	ON_BN_CLICKED(IDM_CAST, OnCast)
	ON_BN_CLICKED(IDM_CONF, OnConf)
	ON_BN_CLICKED(IDM_STARTVIEWER, OnVC10)

	ON_BN_CLICKED(IDC_EXITBUTTON, OnExit)
	ON_LBN_DBLCLK(IDC_CLIENT_LIST, OnDblclkClients)
	ON_MESSAGE(WM_CLIENT_CONNECTED, OnNewClientConnected)
#else //def _NET_VC_
	ON_WM_NCHITTEST()
	ON_WM_LBUTTONDOWN()
	ON_BN_CLICKED(IDC_SLEEP, OnSleep)
#endif //def _NET_VC_
#ifdef _IPR_
	ON_MESSAGE(WM_APP+9, OnRegistIP)
	ON_MESSAGE(WM_APP+10, OnUnregistIP)
#endif // def _IPR_
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRMSServerDlg message handlers
UINT CRMSServerDlg::OnNcHitTest(CPoint point)
{
	CPoint pt = point;
	ScreenToClient(&pt);
	CSize sz = m_SBXLogoSmall.GetBitmapDimension();
	CRect rc(8, 6, 8+sz.cx, 6+sz.cy);
	if(rc.PtInRect(pt))
		return HTCLIENT;
	else
		return CMegaDialog::OnNcHitTest(point);
}

//void crmsserverdlg::onlbuttondown(uint nflags, cpoint point)
//{
//	csize sz = m_sbxlogosmall.getbitmapdimension();
//	crect rc(8, 6, 8+sz.cx, 6+sz.cy);
//	if(rc.ptinrect(point))
//	{
//		caboutdlg dlg;
//		dlg.domodal();
//	}
//	else
//	{
//		cmegadialog::onlbuttondown(nflags, point);
//	}
//}

void CRMSServerDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
	m_bMove = FALSE;
	CRect rct;
	GetWindowRect(&rct);
	if(point.y < 30 && point.x < rct.right-rct.left)
	{
		m_Dragable = TRUE; 
		m_moveOffset = point;
	}
	if(point.y < 348 && point.y > 303 && point.x < 187 && point.x > 137)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
}

//New Dialog UI Dragable DoerIT2015/5/21 -> charith
void CRMSServerDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
	m_Dragable = FALSE;
}
//Right Button down 25-05-2015 CHarith
//void CRMSServerDlg::OnRButtonDown(UINT nFlags, CPoint point)
//{
//		CMegaDialog::OnRButtonDown(nFlags, point);
//}

/*BOOL CRMSServerDlg::DropPopupMenu(UINT nFlags, CPoint point)
{
	m_bMove = FALSE;
	if(m_pMenuPopup || InitializePopupMenu())
	{
		CPoint pt(point);
		if(nFlags != 0) GetCursorPos(&pt);
		m_pMenuPopup->TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, this, NULL);
		return TRUE;
	}
	return FALSE;
}*/

void CRMSServerDlg::OnRButtonDown(UINT nFlags, CPoint point)
{
	//if(!DropPopupMenu(nFlags, point))
		//CMegaDialog::OnRButtonDown(nFlags, point);
	//EnableSettingsMenu();
	//CMegaDialog::OnNcRButtonDown(nFlags, point);
	//OnSysCommand(61587,14811364);
	/*if(pMenuPopup || InitializePopupMenu())
	{*/
		
		/*CPoint pt(point);
		if(nFlags != 0) GetCursorPos(&pt);
		CMenu* pSysMenu = GetSystemMenu(FALSE);
		pSysMenu->TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, this, NULL);*/
		//OnSysCommand(IDM_SETPARAMETERS,14811364); //IDM_SETPARAMETERS 301
		//EnableSettingsMenu();

		
	//}
	
}

//Doerit 2015/05/26 ->Sachith
void CRMSServerDlg::OnIconClick()
{
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	int ItemCount = pSysMenu->GetMenuItemCount();
	bool isAdmin = false;
	CPoint pt;
	if(pSysMenu != 0) GetCursorPos(&pt);

	if(ItemCount <= 4)
	{
		CPasswordDlg dlg;
		dlg.PresetCaption("ƒpƒXƒ[ƒh“ü—Í");//dlg.PresetCaption("Enter password");
		if(dlg.DoModal() == IDOK)
		if(string(dlg.m_strPassword)=="admin")
		{
			EnableSettingsMenu();
			isAdmin = true;
		}
		else MessageBox("Password is incorrect!","Error!",MB_OK);
	} 
	else if(pSysMenu)
	{
		isAdmin = true;
	}

	if(isAdmin)
	{
		pSysMenu->TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, this, NULL);
	}
}

void CRMSServerDlg::OnNcRButtonDown(UINT nFlags, CPoint point)
{
	///if(!DropPopupMenu(nFlags, point))
		//CMegaDialog::OnNcRButtonDown(nFlags, point);
}

#ifdef _NET_VC_

BOOL CRMSServerDlg::OnEraseBkgnd(CDC* pDC)
{
	BOOL bRes = CMegaDialog::OnEraseBkgnd(pDC);

	// different logos
#ifdef _OEM_
	CMegaBitmap * pBmp = &m_PartnerLogo;
#else	// streambox logo
	CMegaBitmap * pBmp = &m_SBXLogo;
#endif

#ifdef _TEC_
	pBmp->DrawTransparent(pDC, m_ptEncoderLogo.x, m_ptEncoderLogo.y, RGB(255, 255, 255));
#else
  #ifdef _GUI2008_
   #ifdef _J707_ //#J7070004 TOMOKOH
	pBmp->DrawTransparent(pDC, m_ptEncoderLogo.x+8,m_ptEncoderLogo.y-9, RGB(255, 0, 0));
   #else
	pBmp->DrawTransparent(pDC, m_ptEncoderLogo.x-342, m_ptEncoderLogo.y-54, RGB(255, 0, 0));
   #endif // def _J707_
  #else
    pBmp->DrawTransparent(pDC, m_ptEncoderLogo.x, m_ptEncoderLogo.y, RGB(255, 0, 0));
  #endif
#endif

#ifdef _VC_J7_
	pBmp = &m_PartnerLogo;
  #ifdef _J707_ // #J7070005 TOMOKOH
	pBmp->DrawTransparent(pDC, m_ptEncoderLogo.x-204, m_ptEncoderLogo.y-30, RGB(255, 255, 255));
  #else
	pBmp->DrawTransparent(pDC, m_ptEncoderLogo.x-204, m_ptEncoderLogo.y-8, RGB(255, 0, 0));
  #endif
#endif

	return bRes;
}

#else //def _NET_VC_

BOOL CRMSServerDlg::OnEraseBkgnd(CDC* pDC)
{
	BOOL bRes = CMegaDialog::OnEraseBkgnd(pDC);

	CRect rc;
	GetClientRect(&rc);
	// vc-10 encoder logo
	CSize sz = m_SBXLogoSmall.GetBitmapDimension();
	m_SBXLogoSmall.Draw(pDC, 8, 6);
	m_EncoderLogo.Draw(pDC, 8+sz.cx+4, 6);

	// different logos
#ifdef _OEM_
	CMegaBitmap * pBmp = &m_PartnerLogo;
#else	// streambox logo
	CMegaBitmap * pBmp = &m_SBXLogo;
#endif

	sz = m_pBackgroundBmp->GetBitmapDimension();
#ifdef _TEC_
	int y = sz.cy-pBmp->GetBitmapDimension().cy-13;
	pBmp->DrawTransparent(pDC, 16, y, RGB(255, 255, 255));
#else
	int y = m_rcPreview.bottom + (sz.cy-m_rcPreview.bottom-pBmp->GetBitmapDimension().cy)/2;
	pBmp->DrawTransparent(pDC, 16, y, RGB(255, 0, 0));
#endif
	return bRes;
}

#endif //def _NET_VC_

int	 CRMSServerDlg::GetControlH(int ID)
{
	CWnd* ctrl;
	RECT rect;
	WINDOWPLACEMENT wp;

	ctrl=GetDlgItem(ID);
	ctrl->GetWindowPlacement(&wp);
	memcpy(&rect,&wp.rcNormalPosition,sizeof(RECT));
	return rect.bottom-rect.top;
}
int  CRMSServerDlg::GetControlW(int ID)
{
	CWnd* ctrl;
	RECT rect;
	WINDOWPLACEMENT wp;

	ctrl=GetDlgItem(ID);
	ctrl->GetWindowPlacement(&wp);
	memcpy(&rect,&wp.rcNormalPosition,sizeof(RECT));
	return rect.right-rect.left;
}

void CRMSServerDlg::SetControlSize(int ID, int w,int h)
{
	CWnd* ctrl;
	RECT rect, wrect;
	WINDOWPLACEMENT wp;
	int x,y;

	ctrl=GetDlgItem(ID);
	ctrl->GetWindowPlacement(&wp);
	memcpy(&rect,&wp.rcNormalPosition,sizeof(RECT));

	GetWindowPlacement(&wp);
	memcpy(&wrect,&wp.rcNormalPosition,sizeof(RECT));

	//center by x
	x=((wrect.right-wrect.left)-(w))/2;
	y=wrect.top;

	ctrl->MoveWindow(x, y, w, h, TRUE);
}
void CRMSServerDlg::MoveControl(int ID, int x,int y)
{
	CWnd* ctrl;
	RECT rect, wrect;
	WINDOWPLACEMENT wp;

	ctrl=GetDlgItem(ID);
	ctrl->GetWindowPlacement(&wp);
	memcpy(&rect,&wp.rcNormalPosition,sizeof(RECT));
	if (x==-1) {
		// center by x
		GetWindowPlacement(&wp);
		memcpy(&wrect,&wp.rcNormalPosition,sizeof(RECT));
		x=((wrect.right-wrect.left)-(rect.right-rect.left))/2;
	}
	ctrl->MoveWindow(x, y, rect.right-rect.left, rect.bottom-rect.top, TRUE);
}

int  CRMSServerDlg::GetControlY(int ID)
{
	CWnd* ctrl;
	RECT rect;
	WINDOWPLACEMENT wp;

	ctrl=GetDlgItem(ID);
	ctrl->GetWindowPlacement(&wp);
	memcpy(&rect,&wp.rcNormalPosition,sizeof(RECT));
	return rect.top;
}

#ifdef _TEC_
BOOL CRMSServerDlg::createGlobal()
{
	SECURITY_ATTRIBUTES sa;
	SECURITY_DESCRIPTOR sd;
	DWORD err;

	if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
		return FALSE;

	// Add a NULL DACL to the security descriptor to allow all access to the object.
	if(!SetSecurityDescriptorDacl(&sd, TRUE, (PACL)NULL, FALSE))
		return FALSE;

	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = &sd;
	sa.bInheritHandle = TRUE;

	m_hGlobal = CreateEvent(&sa, FALSE, TRUE, VC_ENCODER_EXISTANCE_EVENT_NAME);
	err = GetLastError();

	if(m_hGlobal == NULL)
		return FALSE;

	return (err != ERROR_ALREADY_EXISTS);
}
#endif //def _TEC_

BOOL CRMSServerDlg::OnInitDialog()
{
	CMegaDialog::OnInitDialog();

#ifdef _IPR_
	BaseServer.m_bEnableIpr = gEnableIpr;
	InitializeCriticalSection(&BaseServer.m_IprCritical);
#endif //def _IPR_

#ifdef _TEC_
	createGlobal();		// grabs VC encoder existance named event
#endif //def _TEC_

	m_SBXLogoSmall.LoadBitmap(IDB_SBX_LOGO_SMALL);
#ifdef VC70
	m_EncoderLogo.LoadBitmap(IDB_ENCODER_TITLE70);
#else
	m_EncoderLogo.LoadBitmap(IDB_ENCODER_TITLE);
#endif
#ifdef _QFI_
	m_PartnerLogo.LoadBitmap(IDB_QFI);
#endif
#ifdef _VITAL_
	m_PartnerLogo.LoadBitmap(IDB_VITAL);
#endif
#ifdef _TEC_
	m_PartnerLogo.LoadBitmap(IDB_JAEA_LOGO);
#endif

#ifdef _VC_J7_
	m_PartnerLogo.LoadBitmap(IDB_JAEA_LOGO);
  #ifdef _J707_ //#J7070004 - TOMOKOH //Doerit 2015/02/26 -> Sachith
	//m_SBXLogo.LoadBitmap(IDB_POWERED_QFI);
	//m_SBXLogo.LoadBitmap(IDB_POWERED_AXIO);

#else
	m_SBXLogo.LoadBitmap(IDB_POWERED);
  #endif
#else
	m_SBXLogo.LoadBitmap(IDB_SBX_LOGO);
#endif


	CSize szBase = m_pBackgroundBmp->GetBitmapDimension();

	DWORD dwStyle = WS_CHILD|WS_VISIBLE|BS_AUTOCHECKBOX;

#ifdef _NET_VC_

	// Unnamed event to stop/resume sending video stream
	g_hNoVideoEnabled = CreateEvent(NULL, TRUE, TRUE, NULL);

	// video/audio/sleep buttons
	m_VideoBtn.Create("", dwStyle, CRect(), this, IDC_VIDEO);
	m_AudioBtn.Create("", dwStyle, CRect(), this, IDC_AUDIO);
	
#ifndef _GUI2008_
    m_btnVideoSource.Create("", dwStyle, CRect(), this, IDC_VIDEOSOURCE);
    m_btnSetParameters.Create("", dwStyle, CRect(), this, IDC_SETPARAMETERS);
#endif

	m_btnExit.Create("", dwStyle, CRect(), this, IDC_EXITBUTTON);
	m_btnSetting.Create("", dwStyle, CRect(), this,IDC_SETPARAMETERS);// IDC_SETPARAMETERS);
    m_btnWinMinimize.Create("", dwStyle, CRect(), this, IDC_WINDOWMIN); //
	m_btnWinClose.Create("", dwStyle, CRect(), this, IDC_EXITBUTTON); //
	m_btnDlgIcon.Create("", dwStyle, CRect(), this, IDC_ICON);

	m_VideoBtn.SetBitmaps(IDB_VIDEO_DOWN, IDB_VIDEO_DOWN, IDB_VIDEO_OVER_ON, 
						  IDB_VIDEO_OUT, IDB_VIDEO_DOWN, IDB_VIDEO_OVER, IDB_VIDEO_DISABLED);
	m_AudioBtn.SetBitmaps(IDB_AUDIO_DOWN, IDB_AUDIO_DOWN, IDB_AUDIO_OVER_ON, 
						  IDB_AUDIO_OUT, IDB_AUDIO_DOWN, IDB_AUDIO_OVER, IDB_AUDIO_DISABLED);
	m_btnExit.SetBitmaps(IDB_EXIT_OUT, IDB_EXIT_DOWN, IDB_EXIT_OVER,
						 IDB_EXIT_OUT, IDB_EXIT_DOWN, IDB_EXIT_OVER);
	m_btnSetting.SetBitmaps(IDB_CANCEL_OUT, IDB_CANCEL_DOWN, IDB_CANCEL_OVER,
						 IDB_CANCEL_OUT, IDB_CANCEL_DOWN, IDB_CANCEL_OVER);

	m_btnWinMinimize.SetBitmaps(IDB_MIN_OUT, IDB_MIN_OUT, IDB_MIN_OVER,IDB_MIN_OUT, IDB_MIN_OUT, IDB_MIN_OVER);
	m_btnWinClose.SetBitmaps(IDB_CLOSE_OUT, IDB_CLOSE_OUT, IDB_CLOSE_OVER);
	m_btnDlgIcon.SetBitmaps(IDB_DLG_ICON, IDB_DLG_ICON, IDB_DLG_ICON);

	RECT rect;
	m_btnDlgIcon.GetSize(&rect);
	m_btnDlgIcon.MoveWindow(5, 3, rect.right, rect.bottom);

#ifndef _GUI2008_
    m_btnVideoSource.SetBitmaps(IDB_VIDEOSOURCE_OUT, IDB_VIDEOSOURCE_DOWN, IDB_VIDEOSOURCE_OVER,
								IDB_VIDEOSOURCE_OUT, IDB_VIDEOSOURCE_DOWN, IDB_VIDEOSOURCE_OVER, IDB_VIDEOSOURCE_DISABLED);

	m_btnSetParameters.SetBitmaps(IDB_SETPARAMETERS_OUT, IDB_SETPARAMETERS_DOWN, IDB_SETPARAMETERS_OVER,
								  IDB_SETPARAMETERS_OUT, IDB_SETPARAMETERS_DOWN, IDB_SETPARAMETERS_OVER);
#endif

	// clients list
	m_ClientsList.SetBitmaps(IDB_ICON_WHITE, IDB_ICON_WHITE);
	m_ClientsList.Create(
		WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_BORDER|
		LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOTIFY, CRect(), this, IDC_CLIENT_LIST);
	m_ClientsList.SetColors(RGB(255, 255, 255), RGB(102, 102, 102),
							RGB(93, 93, 115), RGB(255, 255, 255));
	m_ClientsList.SetBackColor2(RGB(247, 247, 247));

#else //def _NET_VC_

	// preview window
	m_nInfoBarHeight = 19;
	m_rcPreview = CRect(3, 46, 3+320, 46+240);

	// create pref drawer
	m_PrefDrawer.Create(
		NULL, 
		"preferences", 
		WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|WS_OVERLAPPED|WS_TABSTOP, 
		CRect(0, 0, 1, 1), 
		this, 
		ID_DRAWER_PREF);
#ifdef _OEM_
#ifdef _TEC_
	m_PrefDrawer.SetBitmaps(IDB_PREF_SINGLE_OEM_JAEA, IDB_PREF_SINGLE_OEM_JAEA, IDB_PREF_SINGLE_UN, IDB_PREF_SINGLE_UN);
#else //def _TEC_
	m_PrefDrawer.SetBitmaps(IDB_PREF_SINGLE_OEM, IDB_PREF_SINGLE_OEM, IDB_PREF_SINGLE_UN, IDB_PREF_SINGLE_UN);
#endif //def _TEC_
#else
	m_PrefDrawer.SetBitmaps(IDB_PREF_SINGLE, IDB_PREF_SINGLE, IDB_PREF_SINGLE_UN, IDB_PREF_SINGLE_UN);
#endif
	m_Drawers.push_back(&m_PrefDrawer);

//	initHomePath(); placed after endif

	// video/audio/sleep buttons
	m_VideoBtn.Create("", dwStyle, CRect(), this, IDC_VIDEO);
	m_AudioBtn.Create("", dwStyle, CRect(), this, IDC_AUDIO);
	m_SleepBtn.Create("", dwStyle, CRect(), this, IDC_SLEEP);

	m_VideoBtn.SetBitmaps(IDB_VIDEO_ON_OUT, IDB_VIDEO_ON_DOWN, IDB_VIDEO_ON_OVER, 
						  IDB_VIDEO_OFF_OUT, IDB_VIDEO_OFF_DOWN, IDB_VIDEO_OFF_OVER);
	m_AudioBtn.SetBitmaps(IDB_AUDIO_ON_OUT, IDB_AUDIO_ON_DOWN, IDB_AUDIO_ON_OVER, 
						  IDB_AUDIO_OFF_OUT, IDB_AUDIO_OFF_DOWN, IDB_AUDIO_OFF_OVER);
	m_SleepBtn.SetBitmaps(IDB_SLEEP_ON_OUT, IDB_SLEEP_ON_DOWN, IDB_SLEEP_ON_OVER, 
						  IDB_SLEEP_OFF_OUT, IDB_SLEEP_OFF_DOWN, IDB_SLEEP_OFF_OVER);

	// clients list
	m_ClientsList.SetBitmaps(IDB_ICON_WHITE, IDB_ICON_WHITE);
	m_ClientsList.Create(
		WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_BORDER|
		LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOTIFY, CRect(), this, IDC_CLIENT_LIST);
	m_ClientsList.SetBackColor(RGB(255, 255, 255));

#endif //def _NET_VC_
	initHomePath();


#ifdef _GUI2008_
	m_btnHi.Create("", WS_CHILD|WS_VISIBLE|BS_RADIOBUTTON, CRect(), this, IDC_HI);
	
	m_btnLow.Create("", WS_CHILD|WS_VISIBLE|BS_RADIOBUTTON, CRect(), this, IDC_LOW);

    m_btnHi.SetBitmaps( IDB_HI_ON_DOWN, IDB_HI_ON_DOWN, IDB_HI_ON_DOWN, 
						  IDB_HI_OFF_OUT, IDB_HI_OFF_DOWN, IDB_HI_OFF_OVER);
	m_btnLow.SetBitmaps( IDB_LOW_ON_DOWN, IDB_LOW_ON_DOWN, IDB_LOW_ON_DOWN, 
						  IDB_LOW_OFF_OUT, IDB_LOW_OFF_DOWN, IDB_LOW_OFF_OVER);

#else
    m_btnCast.Create("", WS_CHILD|WS_VISIBLE|BS_RADIOBUTTON, CRect(), this, IDC_CAST);
	m_btnConf.Create("", WS_CHILD|WS_VISIBLE|BS_RADIOBUTTON, CRect(), this, IDC_CONF);

    m_btnCast.SetBitmaps( IDB_CAST_ON_DOWN, IDB_CAST_ON_DOWN, IDB_CAST_ON_DOWN, 
						  IDB_CAST_OFF_OUT, IDB_CAST_OFF_DOWN, IDB_CAST_OFF_OVER);
	m_btnConf.SetBitmaps( IDB_CONF_ON_DOWN, IDB_CONF_ON_DOWN, IDB_CONF_ON_DOWN, 
						  IDB_CONF_OFF_OUT, IDB_CONF_OFF_DOWN, IDB_CONF_OFF_OVER);
#endif



	int nCast = REGISTRY_LoadInt(KEY_CAST_CONF, 1);

	m_bEnableBroadcast = (1 == nCast);
#ifdef _GUI2008_
     // read hi/lo settings from registry
#else
	m_btnCast.SetCheck(m_bEnableBroadcast ? MBS_CHECK:MBS_UNCHECK);
	m_btnConf.SetCheck(m_bEnableBroadcast ? MBS_UNCHECK:MBS_CHECK);
#endif

	// start viewer button
	dwStyle = WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON;

    if(!gUserModeEnabled)
    {
	  m_StartViewerBtn.Create("", dwStyle, CRect(), this, IDC_START_VIEWER);
	  m_StartViewerBtn.SetBitmaps(IDB_START_OUT, IDB_START_DOWN, IDB_START_OVER);
    }


	// set correct region
	AdjustRegion();

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
#ifdef _J707_ // #J7070001 TOMOKOH
		strAboutMenu.LoadString(IDS_ABOUTBOX_JP);
#else
		strAboutMenu.LoadString(IDS_ABOUTBOX);
#endif
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			//pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
#ifdef _GUI2008_
/*
        SettingsMenu.CreatePopupMenu();
        SettingsMenu.AppendMenu(MF_STRING, IDM_SETPARAMETERS, "&Set Parameters...");
        SettingsMenu.AppendMenu(MF_STRING, IDM_VIDEOSOURCE, "&Video Source...");
        SettingsMenu.AppendMenu(MF_STRING, IDM_STARTVIEWER, "Start &Viewer");
        SettingsMenu.AppendMenu(MF_STRING, IDM_CAST, "C&ast");
        SettingsMenu.AppendMenu(MF_STRING, IDM_CONF, "C&onf");
        pSysMenu->AppendMenu(MF_POPUP, (UINT) SettingsMenu.m_hMenu, "S&ettings");
*/
        SettingsMenuAvailable = false;
#ifdef _J707_ //#J7070001 - TOMOKOH
        pSysMenu->AppendMenu(MF_STRING, IDM_ENABLESETTINGS, "ƒpƒ‰ƒ[ƒ^Ý’è");
#else
        pSysMenu->AppendMenu(MF_STRING, IDM_ENABLESETTINGS, "&Enable Settings...");
#endif
/*
        if(nCast==1)
        {
          SettingsMenu.CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_CHECKED);
          SettingsMenu.CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_UNCHECKED);

//          SettingsMenu.RemoveMenu(IDM_CONF, MF_BYCOMMAND);
        } else
        {
          SettingsMenu.CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_UNCHECKED);
          SettingsMenu.CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_CHECKED);
        }
*/
#endif
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	BaseServer.SetRecordState(FALSE);
	*GET_SERVER_DLG->pSzAudio=10;
	*GET_SERVER_DLG->pSzVideo=0;


	LONG lnRes;
	HKEY hKey;
	DWORD lLen;
	DWORD dwType;
	DWORD value;

	QUALITY=50;

	BaseServer.LoadPassword();
	BaseServer.SetOutListBox(&m_ClientsList);

	lnRes = RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,KEY_ALL_ACCESS,&hKey);
	if(ERROR_SUCCESS == lnRes)
	{
		lLen = sizeof(DWORD);
		lnRes = RegQueryValueEx(hKey,"IP Server",0,&dwType,(BYTE*)&(value),&lLen);
		if(ERROR_SUCCESS == lnRes)
		{
            if(bindIP==1)
              m_host.DefaultIP(value);
            else
              m_host.DefaultIP(bindIP);
			DWORD dwIP = m_host.DefaultIP();

			if(dwIP != value)
			{
				lnRes = RegSetValueEx(hKey,"IP Server",NULL,REG_DWORD,(BYTE*)&( dwIP ),sizeof(DWORD));
			}
		}
		else
		{
			//m_strIP = GetIPStr(INADDR_ANY); // Load from Registry
            if(bindIP==1)
              m_host.DefaultIP(INADDR_ANY);
            else
              m_host.DefaultIP(bindIP);
			DWORD dwIP = m_host.DefaultIP();

			lnRes = RegSetValueEx(hKey,"IP Server",NULL,REG_DWORD,(BYTE*)&( dwIP ),sizeof(DWORD));
		}

		String str;
		m_host.DefaultIPString(str);
		m_strIP = str.c_str();
		BaseServer.setSelectedAddr(m_strIP);

		lLen = sizeof(DWORD);
		lnRes = RegQueryValueEx(hKey,"Port Server",0,&dwType,(BYTE*)&(value),&lLen);
		if(ERROR_SUCCESS == lnRes)
		{
			m_nPort = value;
		}
		else
		{
			m_nPort = 777;
		}

		lLen = sizeof(DWORD);
		lnRes = RegQueryValueEx(hKey,"Bit rate",0,&dwType,(BYTE*)&(value),&lLen);
		if(ERROR_SUCCESS == lnRes)
		{
			LOGRUS_reqbitrate = ((double)(value * 30)) / 1024.0;
		}
		else
		{
			LOGRUS_reqbitrate = 1;
		}
#ifdef _CYCLIC_BUFFER_
		lLen = sizeof(DWORD);
		lnRes = RegQueryValueEx(hKey,"Cycle",0,&dwType,(BYTE*)&(value),&lLen);
		if(ERROR_SUCCESS == lnRes)
		{
			BaseServer.SetRecordCycle(value);
		}
		else
		{
			BaseServer.SetRecordCycle(2);
		}
#endif
		lLen = sizeof(DWORD);
		lnRes = RegQueryValueEx(hKey,"Frame rate",0,&dwType,(BYTE*)&(value),&lLen);
		if(ERROR_SUCCESS == lnRes)
		{
			m_nCurrentFPS = (int)value;
		}
		else
		{
			m_nCurrentFPS = 15;
		}

		RegCloseKey(hKey);
	}
	else
	{

		m_host.DefaultIP(INADDR_ANY);
		String str;
		m_host.DefaultIPString(str);
		m_strIP = str.c_str();

		m_nPort = 777;
		LOGRUS_reqbitrate = 1;
		m_nCurrentFPS = 15;
	}


	mainHandle=0;
	
	//////////////////////////////////////
	timeStart = timeGetTime();
	SetTimer(2,1000,0);
#ifdef _CYCLIC_BUFFER_
	BaseServer.InitStorage();
	SetTimer(3,2000,0);
#endif

	ShowInfoBar();


	SetFocus();

	// enabvle audio/video in the start
	m_bVideo=TRUE;
	m_bAudio=TRUE;

    if (!InitOutput(b640x480))
        return FALSE;

    // load sleep image from RMS-compressed file
    char filename[1000];
    char *fn2;
    GetModuleFileName(0,filename,1000);

    fn2=strrchr(filename,'\\');
    fn2[0]=0;

    strcat(filename,"\\default.sleep");

    FILE *f;
    f = fopen(filename,"rb");
    if (f) {
        int size=filelength(fileno(f));        
        pSleepBitmapDataCompressed = (BYTE*)malloc(size);
        fread(pSleepBitmapDataCompressed,size,1,f);
        fclose(f);
        sizeSleepCompressed=size;
    }

	char buf[6];
	BaseServer.ListenInit(static_cast<LPCTSTR>(m_strIP), itoa(m_nPort, buf, 10));
	if(!BaseServer.ListenStart())
	{
		KillTimer(2);

		MessageBox("Unable to start server.","Error",MB_OK | MB_ICONERROR);
		EndDialog(0);
		return FALSE;
	}

	// after all controls correctly placed - set parent's background for them
	m_VideoBtn.SetBackgroundBmp(m_pBackgroundBmp);
	m_AudioBtn.SetBackgroundBmp(m_pBackgroundBmp);

    if(!gUserModeEnabled)
    {
	  m_StartViewerBtn.SetBackgroundBmp(m_pBackgroundBmp);
    }

#ifdef _GUI2008_
    m_btnHi.SetBackgroundBmp(m_pBackgroundBmp);
	m_btnLow.SetBackgroundBmp(m_pBackgroundBmp);

    if( m_nCurrentFPS==presetFpsLow )
    {
      m_btnLow.SetCheck(MBS_CHECK);
      m_btnHi.SetCheck(MBS_UNCHECK);
    } else
    if(m_nCurrentFPS==presetFpsHi)
    {
      m_btnHi.SetCheck(MBS_CHECK);
      m_btnLow.SetCheck(MBS_UNCHECK);
    }
#else
	m_btnCast.SetBackgroundBmp(m_pBackgroundBmp);
	m_btnConf.SetBackgroundBmp(m_pBackgroundBmp);
#endif


	int nPassLen = BaseServer.GetPasswordLen();
	char * pszPass = new char[nPassLen+1];
	BaseServer.GetPassword(pszPass);

#ifdef _NET_VC_

	CStringList list;
	IPArr arr;
	m_host.GetIPArr(arr);
	for(IPArr::const_iterator it = arr.begin(); it != arr.end(); it++)
	{
		String str = (*it).second;
		list.AddTail(str.c_str());
	}
	String str;
	m_host.DefaultIPString(str);
	m_spDlg.PresetIPAddress(&list, str.c_str());
	m_spDlg.PresetBitRate(LOGRUS_reqbitrate*1024/30);
	m_spDlg.PresetPassword(pszPass);
	m_spDlg.PresetPort(m_nPort);
	m_spDlg.PresetFrameRate(m_nCurrentFPS);

	m_hMutex = CreateMutex(NULL, FALSE, ENCODER_MUTEX_NAME);
	if(WaitForSingleObject(m_hMutex, 5000) != WAIT_TIMEOUT)
	{
		WinPlace wp;
		m_addr = _T("none");
		wp.Restore(this, ENCODER_REGISTRY_KEY, m_addr);
		ReleaseMutex(m_hMutex);
	}

#else //def _NET_VC_

	m_SleepBtn.SetBackgroundBmp(m_pBackgroundBmp);

	m_PrefDrawer.SetServerParams(&m_host, m_nPort, BaseServer.GetRecordCycle());
	m_PrefDrawer.SetPassword(pszPass);
	m_PrefDrawer.SetBitrate(LOGRUS_reqbitrate*1024/30);
	m_PrefDrawer.SetFPS(m_nCurrentFPS);
	m_PrefDrawer.SetFrameSize(b640x480);
#if defined(_OEM_) && defined(_TEC_)
	m_PrefDrawer.SetHomePath(getHomePath());
#endif //defined(_OEM_) && defined(_TEC_)

#endif //def _NET_VC_

	delete pszPass;

    if(DisableFEC)
    {
      REGISTRY_SaveInt(KEY_FEC_ENABLED, false);
      FECparam1 = REGISTRY_LoadInt(KEY_FEC_PARAM1, FECparam1);
      FECparam2 = REGISTRY_LoadInt(KEY_FEC_PARAM2, FECparam2);
      EnableFEC = 0;
    } else
    {
      if(EnableFEC==0)
      {
        EnableFEC = REGISTRY_LoadInt(KEY_FEC_ENABLED, EnableFEC);
        FECparam1 = REGISTRY_LoadInt(KEY_FEC_PARAM1, FECparam1);
        FECparam2 = REGISTRY_LoadInt(KEY_FEC_PARAM2, FECparam2);
      } else
      {
        REGISTRY_SaveInt(KEY_FEC_ENABLED, EnableFEC);
        REGISTRY_SaveInt(KEY_FEC_PARAM1, FECparam1);
        REGISTRY_SaveInt(KEY_FEC_PARAM2, FECparam2);
      }
    }
	return TRUE;  // return TRUE  unless you set the focus to a control
}

bool CRMSServerDlg::InitOutput(bool isVideo_v2)
{
	if (mainHandle==0) 
        // ininializing for the first time
		mainHandle=this->GetSafeHwnd();    
    else {
        capPVR_Abort();
	}

    int idCap=13567;
    CAPLIBCREATESTRUCT cs;
    
    m_AudioDevicePresent=TRUE;
    m_VideoDevicePresent=TRUE;
    
    
    ::ZeroMemory(&cs, sizeof(CAPLIBCREATESTRUCT));
    if (!isVideo_v2) {
        cs.w = 320;
        cs.h = 240;
        cs.pParent = &mainHandle;
    } 
    else {
        cs.w = 720;
        cs.h = 480;
        cs.pParent = &mainHandle;
    }
    cs.nID = IDC_PREVIEW;
    cs.nFPS = m_nCurrentFPS;
    cs.szDriverName = "";
    
    if(!capPVR_Create(&cs))
    {
	  #if defined(_J707_) && defined(_UI_JP_) //#103R210023
        MessageBox("ƒrƒfƒIƒJƒƒ‰‚Ì‹N“®‚ÉŽ¸”s‚µ‚Ü‚µ‚½BPC ‚ÉƒJƒƒ‰‚Æƒ}ƒCƒN(ƒ}ƒCƒN‚Í•K‚¸Ú‘±‚µ‚Ä‚­‚¾‚³‚¢)‚ª³í‚É“®ì‚µ‚Ä‚¢‚é‚©Šm”F‚µ‚Ä‚­‚¾‚³‚¢B"
			,"Error",MB_OK | MB_ICONERROR);
	  #else
        MessageBox("Unable to open video capture/audio device.","Error",MB_OK | MB_ICONERROR);
	  #endif
        EndDialog(0);
        return false;
    }
    
    if(!capPVR_GetDeviceMode())
    {
        m_VideoDevicePresent=0;
        DisableVideoButtons();
		SetTimer(4, 2000, NULL);
    }
    
    //------------ init capture and set timer -----------------------
    capPVR_SetCallback(Process);
    StartLive();
    
    if (isVideo_v2) 
	{
        *BaseServer.GetDataPtr_TypeVideo(0) = TAG_RMSVIDEO_v02;
    }
    else 
	{
        *BaseServer.GetDataPtr_TypeVideo(0) = TAG_RMSVIDEO_v01;
    }

  #ifdef _J707_
	//
	// #J7070022
	LoadEncoderParam();
  #endif
	UpdateFeedStatus();

#ifdef _NET_VC_

	// specify controls' layout for different skins
    if( isVideo_v2 ) 
	{
	}
	else
	{
		m_rcPreview.SetRect(10, 35+20, 10+320, 35+260);
		m_rcInfoBar.SetRect(10, 10+20, 10+320, 10+39);
		m_rcClientsList.SetRect(340, 34+20, 492, 258+20);
		m_ptClientCounter.SetPoint(436, 276);
		m_ptEncoderLogo.SetPoint(341, 331);
		m_ptStartViewer.SetPoint(369, 289);
#ifdef _GUI2008_
    	m_ptHi.SetPoint(135, 289);
		m_ptLow.SetPoint(180, 289);
#else
    	m_ptVideoSource.SetPoint(10, 287);
    	m_ptSetParameters.SetPoint(230, 322);
    	m_ptCast.SetPoint(125, 289);
		m_ptConf.SetPoint(170, 289);
#endif
		m_ptVideo.SetPoint(230, 287);
		m_ptAudio.SetPoint(286, 287);
		m_ptExit.SetPoint(10, 322);
	}

    // set correct height and width of the frame
	CWnd * pPreviewWnd = GetDlgItem(IDC_PREVIEW);
	pPreviewWnd->MoveWindow(&m_rcPreview);
	m_ClientsList.MoveWindow(&m_rcClientsList);

	// move video/audio buttons
	RECT rect;
	m_AudioBtn.GetSize(&rect);
	m_AudioBtn.MoveWindow(m_ptAudio.x, m_ptAudio.y+20, rect.right, rect.bottom);
	m_VideoBtn.GetSize(&rect);
	m_VideoBtn.MoveWindow(m_ptVideo.x + 10, m_ptVideo.y+20, rect.right, rect.bottom);
#ifndef _GUI2008_
	m_btnVideoSource.GetSize(&rect);
	m_btnVideoSource.MoveWindow(m_ptVideoSource.x, m_ptVideoSource.y, rect.right, rect.bottom);
	m_btnSetParameters.GetSize(&rect);
	m_btnSetParameters.MoveWindow(m_ptSetParameters.x, m_ptSetParameters.y, rect.right, rect.bottom);
#endif

	m_btnExit.GetSize(&rect);
	m_btnExit.MoveWindow(m_ptExit.x+420, m_ptExit.y-20, rect.right, rect.bottom);
	m_btnSetting.GetSize(&rect);
	m_btnSetting.MoveWindow(m_ptExit.x+360, m_ptExit.y-20, rect.right, rect.bottom);
	m_btnWinMinimize.GetSize(&rect);
	m_btnWinMinimize.MoveWindow(m_ptExit.x+420, m_ptExit.y-320, rect.right, rect.bottom);
	m_btnWinClose.GetSize(&rect);
	m_btnWinClose.MoveWindow(m_ptExit.x+442, m_ptExit.y-320, rect.right, rect.bottom);

	

    if(!gUserModeEnabled)
    {
	  m_StartViewerBtn.GetSize(&rect);
	  m_StartViewerBtn.MoveWindow(m_ptStartViewer.x, m_ptStartViewer.y, rect.right, rect.bottom);
    }

#ifdef _GUI2008_
    m_btnHi.GetSize(&rect);
	m_btnHi.MoveWindow(m_ptHi.x-126, m_ptHi.y+20, rect.right, rect.bottom);
	m_btnLow.GetSize(&rect);
	m_btnLow.MoveWindow(m_ptLow.x-126, m_ptLow.y+20, rect.right, rect.bottom);
#else
    m_btnCast.GetSize(&rect);
	m_btnCast.MoveWindow(m_ptCast.x, m_ptCast.y, rect.right, rect.bottom);
	m_btnConf.GetSize(&rect);
	m_btnConf.MoveWindow(m_ptConf.x, m_ptConf.y, rect.right, rect.bottom);
#endif

#else //def _NET_VC_

    // set correct height and width of the frame
	CWnd * pPreviewWnd = GetDlgItem(IDC_PREVIEW);
//	pPreviewWnd->SetWindowPos(NULL, m_rcPreview.left, m_rcPreview.top, 
//		m_rcPreview.Width(), m_rcPreview.Height(), SWP_NOZORDER);
	pPreviewWnd->MoveWindow(&m_rcPreview);

	// move min/max/close buttons
	CRect rcClient;
	GetClientRect(&rcClient);
	CRect rc;
	m_CloseBtn.GetWindowRect(&rc);
	int w = rc.Width();
	int h = rc.Height();
	int x = rcClient.right - 8 - w;
	int y = rcClient.top + 8;
	m_CloseBtn.MoveWindow(x, y, w, h, TRUE);
	x -= w + 4;
	m_MaxBtn.MoveWindow(x, y, w, h, TRUE);
	x -= w + 4;
	m_MinBtn.MoveWindow(x, y, w, h, TRUE);

	// move video/audio/sleep buttons
	m_SleepBtn.GetWindowRect(&rc);
	w = rc.Width();
	h = rc.Height();
	x = m_rcPreview.right - w-2;
	y = m_rcPreview.bottom + 6;
	m_SleepBtn.MoveWindow(x, y, w, h);
	x -= (w+4);
	m_AudioBtn.MoveWindow(x, y, w, h);
	x -= w;
	m_VideoBtn.MoveWindow(x, y, w, h);


	CRect rcBtn;
#ifdef _GUI2008_
    m_btnHi.SetWindowPos(NULL, m_rcPreview.right-92, m_rcPreview.bottom+31, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
	m_btnHi.GetWindowRect(&rcBtn);
	m_btnLow.SetWindowPos(NULL, m_rcPreview.right-92+rcBtn.Width(), m_rcPreview.bottom+31, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
#else
    m_btnCast.SetWindowPos(NULL, m_rcPreview.right-92, m_rcPreview.bottom+31, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
	m_btnCast.GetWindowRect(&rcBtn);
	m_btnConf.SetWindowPos(NULL, m_rcPreview.right-92+rcBtn.Width(), m_rcPreview.bottom+31, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
#endif
	// clients list
	w = rcClient.right-m_rcPreview.right-6;
	h = m_rcPreview.Height()-m_nInfoBarHeight;
	m_ClientsList.SetWindowPos(NULL, m_rcPreview.right+2, m_rcPreview.top, w, h, SWP_NOZORDER);

	// start viewer button
    if(!gUserModeEnabled)
    {
	  CSize sz = m_pBackgroundBmp->GetBitmapDimension();
      m_StartViewerBtn.GetWindowRect(&rc);
	  m_StartViewerBtn.SetWindowPos(NULL, sz.cx-rc.Width()-16, sz.cy-rc.Height()-16, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
    }

#endif //def _NET_VC_

    return true;
}


void CRMSServerDlg::EnableSettingsMenu()
{
  if(!SettingsMenuAvailable)
  {
    SettingsMenuAvailable = true;

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    pSysMenu->RemoveMenu(IDM_ENABLESETTINGS, MF_BYCOMMAND);

    SettingsMenu.CreatePopupMenu();
#ifdef _J707_ //#J7070001 - TOMOKOH
    pSysMenu->AppendMenu(MF_STRING, IDM_SETPARAMETERS, "ƒpƒ‰ƒ[ƒ^Ý’è");
    pSysMenu->AppendMenu(MF_STRING, IDM_VIDEOSOURCE, "ƒrƒfƒIƒ\[ƒX");
    pSysMenu->AppendMenu(MF_STRING, IDM_STARTVIEWER, "ƒrƒ…[ƒA‹N“®");
    pSysMenu->AppendMenu(MF_STRING, IDM_CAST, "ƒLƒƒƒXƒgƒ‚[ƒh");
    pSysMenu->AppendMenu(MF_STRING, IDM_CONF, "‰ï‹cƒ‚[ƒh");
    //pSysMenu->AppendMenu(MF_POPUP, (UINT) SettingsMenu.m_hMenu, "Ý’è");

#else
    SettingsMenu.AppendMenu(MF_STRING, IDM_SETPARAMETERS, "&Set Parameters...");
    SettingsMenu.AppendMenu(MF_STRING, IDM_VIDEOSOURCE, "&Video Source...");
    SettingsMenu.AppendMenu(MF_STRING, IDM_STARTVIEWER, "Start &Viewer");
    SettingsMenu.AppendMenu(MF_STRING, IDM_CAST, "C&ast");
    SettingsMenu.AppendMenu(MF_STRING, IDM_CONF, "C&onf");
    pSysMenu->AppendMenu(MF_POPUP, (UINT) SettingsMenu.m_hMenu, "S&ettings");
#endif
    if(m_bEnableBroadcast)
    {
      pSysMenu->CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_CHECKED);
      pSysMenu->CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_UNCHECKED);
    } else
    {
      pSysMenu->CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_UNCHECKED);
      pSysMenu->CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_CHECKED);
    }
    //OnSetParameters();
/*  CRect rect;
    GetWindowRect(&rect);
    rect.top+=GetSystemMetrics(SM_CYCAPTION);
    pSysMenu->TrackPopupMenu(TPM_LEFTALIGN,rect.left,rect.top,this,NULL);
*/
	//#J7070016: copy from DisableDialogButton()
	if(!capPVR_GetDeviceMode())
	{
      pSysMenu->EnableMenuItem(IDM_VIDEOSOURCE, MF_BYCOMMAND | MF_GRAYED);
	}

  }
}




void CRMSServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	CRect rct;
	GetWindowRect(&rct);
	//if(point.y < 30 && point.x < rct.right-rct.left)
	//{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	} else
#ifdef _GUI2008_
    if (nID==IDM_SETPARAMETERS)
    {
      OnSetParameters();
    } else
    if (nID==IDM_VIDEOSOURCE)
    {
      OnVideoSource();
    } else
    if (nID==IDM_CAST)
    {
      SettingsMenu.CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_CHECKED);
      SettingsMenu.CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_UNCHECKED);
      OnCast();
    } else
    if (nID==IDM_CONF)
    {
      SettingsMenu.CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_UNCHECKED);
      SettingsMenu.CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_CHECKED);
      OnConf();
    } else
    if (nID==IDM_STARTVIEWER)
    {
      CallViewer("");
    } else
    if (nID==IDM_ENABLESETTINGS)
    {
      CPasswordDlg dlg;
	#ifdef _J707_ //#J7070001 - TOMOKOH
      dlg.PresetCaption("ƒpƒXƒ[ƒh“ü—Í");
	#else
      dlg.PresetCaption("Enter password");
	#endif
      if(dlg.DoModal() == IDOK)
        if(string(dlg.m_strPassword)=="admin")
          EnableSettingsMenu();
        else
          MessageBox("Password is incorrect!","Error!",MB_OK);
    } else
#endif
	{
		CMegaDialog::OnSysCommand(nID, lParam);
	}
//}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRMSServerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CMegaDialog::OnPaint();
		ShowInfoBar();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRMSServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CRMSServerDlg::ShowClientCount()
{
//	m_strTotal.Format("%d clients",BaseServer.GetClientCount());
	UpdateData(FALSE);
}

void CRMSServerDlg::OnTimer(UINT nIDEvent) 
{
	int i;
	switch(nIDEvent)
	{
	case 1:
		KillTimer(1);
		for(i = 0; i<10; i++)
		{
			if(capPVR_SetVideoSource()) break;
			Sleep(100);
		}
		StartLive();
		break;
	case 2:
		if (m_bVideo==FALSE) {
			SetCustomImage();
		}

		ShowInfoBar();
		ShowClientCount();

// Deleting passive clients
		BaseServer.DeletePassiveClients();
		BaseServer.UpdateListBox();
		break;
#ifdef _CYCLIC_BUFFER_
	case 3:
		BaseServer.CheckDeleteOldFiles();
		break;
#endif

#ifdef _NET_VC_
	case 4:
		KillTimer(4);
		if(g_hNoVideoEnabled) ResetEvent(g_hNoVideoEnabled);
		break;

	default:
		if((nIDEvent >= MIN_TIMER_EVENT_ID) && (nIDEvent < MIN_TIMER_EVENT_ID+256))
		{
//			KillTimer(nIDEvent);
//			BaseServer.ClientEnableNoVideo(nIDEvent - MIN_TIMER_EVENT_ID, TRUE); - what's for ???
		}
#endif //def _NET_VC_
	}


	CMegaDialog::OnTimer(nIDEvent);
}

#ifdef _NET_VC_
LRESULT CRMSServerDlg::OnNewClientConnected(WPARAM wParam, LPARAM lParam)
{
	if((lParam == 0) && (wParam < 256))
	{
		SetTimer(wParam + MIN_TIMER_EVENT_ID, 2000, NULL);
	}
//    UpdateFeedStatus(); - useless
	return 0;
}

void CRMSServerDlg::OnSetParameters()
{
	CString oldIP = m_spDlg.GetIPAddress();
	CString oldPass = m_spDlg.GetPassword();
	int oldPort = m_spDlg.GetPort();
	int oldBR = m_spDlg.GetBitRate();
	int oldFR = m_spDlg.GetFrameRate();
    int oldfec = EnableFEC+FECparam2*3+FECparam1*1000;

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	int ItemCount = pSysMenu->GetMenuItemCount();
	bool isAdmin = false;

	if(ItemCount <= 3)
	{
		CPasswordDlg dlg;
		dlg.PresetCaption("ƒpƒXƒ[ƒh“ü—Í");//dlg.PresetCaption("Enter password");
		if(dlg.DoModal() == IDOK)
		if(string(dlg.m_strPassword)=="admin")
		{
			EnableSettingsMenu();
			isAdmin = true;
		}
		else MessageBox("Password is incorrect!","Error!",MB_OK);
	} 
	else
	{
		isAdmin = true;
	}

	if(isAdmin)
	{
		if( m_spDlg.DoModal() == IDOK )
		{

			int newfec = EnableFEC+FECparam2*3+FECparam1*1000;
			// check server params
			CString newIP = m_spDlg.GetIPAddress();
			int newPort = m_spDlg.GetPort();
			if((newPort != m_nPort) ||
			   (oldIP && newIP && !newIP.IsEmpty() && (0 != newIP.Compare(oldIP))) || (newfec!=oldfec) )
			{
				m_nPort = newPort;
				m_strIP = newIP;
				UpdateServer(m_strIP, m_nPort);

				/*
				if (*BaseServer.GetDataPtr_TypeVideo(0)==TAG_RMSVIDEO_v02) {
					if (dlg->m_rb320==0)
						InitOutput(false);
				}
				else {
					if (dlg->m_rb640==0) {
						InitOutput(true);
					   // InitOutput(true);
					}
				}
				*/
				StartLive();
			}

			// check password
			CString newPass =  m_spDlg.GetPassword();
			if(oldPass && newPass && !newPass.IsEmpty() && (0 != newPass.Compare(oldPass)))
			{
				BaseServer.SetPassword(newPass);
				BaseServer.SavePassword();
			}

			// check bitrate
			int newBR = m_spDlg.GetBitRate();
			bool changeflag = false;

			if(newBR != oldBR) changeflag=true;
			int newFR = m_spDlg.GetFrameRate();

			if(newFR != oldFR)
			{
			  if(newFR==presetFpsLow)
			  {
				m_btnLow.SetCheck(MBS_CHECK);
				m_btnHi.SetCheck(MBS_UNCHECK);
			  } else
			  if(newFR==presetFpsHi)
			  {
				m_btnHi.SetCheck(MBS_CHECK);
				m_btnLow.SetCheck(MBS_UNCHECK);
			  } else
			  {
				m_btnHi.SetCheck(MBS_UNCHECK);
				m_btnLow.SetCheck(MBS_UNCHECK);
			  }
			  changeflag=true;

			}
			if (changeflag) ChangeBitsAndFps(newBR, newFR);
		}
	}
}

#endif //def _NET_VC_

LRESULT CRMSServerDlg::OnSelectVideoSource(WPARAM wParam, LPARAM lParam)
{
	//bDisableCallback = true;
	//StopLive();
	//SetTimer(1, 30, 0);
    capPVR_Stop();

    int c=0;
    for (c=0; c<50; c++)
    {
      if (capPVR_SetVideoSource()) break;
      Sleep(1);
    }

//	if (!capPVR_SetVideoSource()) 
//		capPVR_SetVideoSource(); // has to be called twice for some cards
	capPVR_Start();

	return 0;
}

#ifdef _NET_VC_
void CRMSServerDlg::OnVideoSource()
{
	OnSelectVideoSource(0, 0);
}
#endif //def _NET_VC_

BOOL CRMSServerDlg::DestroyWindow() 
{
	capPVR_Abort();
	BaseServer.CloseRecordDlg();
	CMegaDialog::DestroyWindow();
	return 1;
}



void CRMSServerDlg::ShowInfoBar()
{
//	m_strBitrate.Format("%.1f kbps",(float)nCaptureBitrate);
//	UpdateData(FALSE);

#ifdef _NET_VC_

	CRect rcInfo = m_rcInfoBar;

#else //def _NET_VC_

	CRect rcInfo(
		m_rcPreview.left-1, 
		m_rcPreview.top-m_nInfoBarHeight-1, 
		m_rcPreview.left+m_rcPreview.Width(), 
		m_rcPreview.top-1);

#endif //def _NET_VC_

	CClientDC dc(this);

	/*
	CRgn rgClip;
	rgClip.CreateRectRgn(rcInfo.left, rcInfo.top, rcInfo.right, rcInfo.bottom);
	dc.SelectClipRgn(&rgClip, RGN_COPY);
	*/

	dc.FillSolidRect(&rcInfo, RGB(93, 93, 115));
	dc.SetTextColor(RGB(210, 210, 210));
	dc.SetBkColor(RGB(93, 93, 115));

	// host, IP
	CString str;
	char pszHostName[1024];
	gethostname(pszHostName, 1024);
	str.Format("%s(%s)", pszHostName, m_strIP);
	CSize sz = dc.GetTextExtent(str);
	int x = rcInfo.left+5;
	int y = rcInfo.top+(rcInfo.bottom-rcInfo.top-sz.cy)/2;
	dc.TextOut(x, y, str);

	// bitrate, fps
	str.Format("%d kbit  %dfps", nCaptureBitrate, nFrameRate);
	sz = dc.GetTextExtent(str);
	x = rcInfo.right-sz.cx-5;
	y = rcInfo.top+(rcInfo.bottom-rcInfo.top-sz.cy)/2;
	dc.TextOut(x, y, str);

	// connected clients
	str.Format("%d", m_ClientsList.GetCount());
	sz = dc.GetTextExtent(str);
#ifdef _NET_VC_
	x = m_ptClientCounter.x - sz.cx;
	y = m_ptClientCounter.y - sz.cy;
#else //def _NET_VC_
	x = 429 - sz.cx;
	y = 284 - sz.cy/2;
#endif //def _NET_VC_
	dc.SetBkMode(TRANSPARENT);
	dc.SetTextColor(RGB(41, 41, 51));
	// erase background first
	CDC dcMem;
	dcMem.CreateCompatibleDC(&dc);
	CGdiObject * pOldBmp = dcMem.SelectObject(m_pBackgroundBmp);
	dc.BitBlt(x, y, sz.cx, sz.cy, &dcMem, x, y, SRCCOPY);
	dcMem.SelectObject(pOldBmp);
	dc.TextOut(x, y, str);

#ifdef _NET_VC_

#ifndef _VC_J7_
	str.Format("NetVC Encoder: %d clients", m_ClientsList.GetCount());
#else
  #ifdef _GUI2008_
   // #J7070014 : TOMOKOH
   #ifdef _J707_
	#ifdef _J707PROD_
		if (!capPVR_GetDeviceMode()) //#J7070018
		{
			if(gUserModeEnabled)
			  str.Format("VC-J707 Encoder (User Mode) Audio Only: %d clients", m_ClientsList.GetCount());
			else
			  str.Format("VC-J707 Encoder: Audio Only %d clients", m_ClientsList.GetCount());
		} else {
			if(gUserModeEnabled)
			  str.Format("VC-J707 Encoder (User Mode): %d clients", m_ClientsList.GetCount());
			else
			  str.Format("VC-J707 Encoder: %d clients", m_ClientsList.GetCount());
		}
	#else
		if (!capPVR_GetDeviceMode()) //#J7070018
		{
			if(gUserModeEnabled)
			  str.Format("VC-J7 Encoder: Audio Only %d clients", m_ClientsList.GetCount()); //remove (User Mode) Text Doerit 2015/02/26 ->Sachith
			else
			  str.Format("VC-J7 Encoder: Audio Only %d clients", m_ClientsList.GetCount());
		} else {
			if(gUserModeEnabled)
			  str.Format("VC-J7 Encoder: %d clients", m_ClientsList.GetCount()); //remove (User Mode) Text Doerit 2015/02/26 ->Sachith
			else
			  str.Format("VC-J7 Encoder: %d clients", m_ClientsList.GetCount());
		}
	#endif
   #else
    if(gUserModeEnabled)
      str.Format("VC-J7 Encoder (User Mode): %d clients", m_ClientsList.GetCount());
    else
      str.Format("VC-J7 Encoder: %d clients", m_ClientsList.GetCount());
   #endif
  #else
	str.Format("VC-J7 Encoder: %d clients", m_ClientsList.GetCount());
  #endif
#endif


#elif defined VC70
	str.Format("VC70 Encoder: %d clients", m_ClientsList.GetCount());
#else
	str.Format("VC10 Encoder: %d clients", m_ClientsList.GetCount());
#endif
	SetWindowText((LPCSTR) str);

	CRect rc;
	GetClientRect(&rc);
}

void CRMSServerDlg::OnSetserver() 
{
	StopLive();
	CSetServerDlg* dlg = new CSetServerDlg(&m_host);

    if (*BaseServer.GetDataPtr_TypeVideo(0)==TAG_RMSVIDEO_v02) {
        dlg->m_rb640=0;
        dlg->m_rb320=-1;
    }
    else {
        dlg->m_rb640=-1;
        dlg->m_rb320=0;
    }

    UpdateData(false);
	// Show set server window
	int response=dlg->DoModal();

    
	if (response==IDOK) {
		CString new_port;
		new_port.Format("%d",dlg->m_nPort);
		// check if we need to restart whole server
		if ( (dlg->strIP!=m_strIP) || (new_port != m_nPort)) 
			UpdateServer((LPCTSTR) dlg->strIP, dlg->m_nPort);

        if (*BaseServer.GetDataPtr_TypeVideo(0)==TAG_RMSVIDEO_v02) {
            if (dlg->m_rb320==0)
                InitOutput(false);
        }
        else {
            if (dlg->m_rb640==0) {
                InitOutput(true);
               // InitOutput(true);
            }
        }

		bDisableCallback = false;
	//	SetCustomImage();
		bDisableCallback = true;
	}
	StartLive();
	delete dlg;		
}


void CRMSServerDlg::UpdateServer(const char *szIP, UINT nPort)
{
	if(!szIP) return;
	bDisableCallback = true;
	//StopLive();

	LONG lnRes;
	HKEY hKey;
	DWORD dwDisp;
	DWORD value;

	m_strIP = szIP;
	m_nPort = nPort;

	BaseServer.ListenStop();

	char buf[6];
	BaseServer.ListenInit(static_cast<LPCTSTR>(m_strIP), itoa(m_nPort, buf, 10));

	lnRes = RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,KEY_ALL_ACCESS,&hKey);
	if(ERROR_SUCCESS != lnRes)
	{
		lnRes = RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,NULL,
			REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisp);
		if(ERROR_SUCCESS != lnRes)
		{
			RegCloseKey(hKey);
			return;
		}
	}

	value = (DWORD)(inet_addr(szIP));
	lnRes = RegSetValueEx(hKey,"IP Server",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	if(ERROR_SUCCESS != lnRes)
	{
		RegCloseKey(hKey);
		return;
	}

	value = (DWORD)(nPort);
	lnRes = RegSetValueEx(hKey,"Port Server",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	if(ERROR_SUCCESS != lnRes)
	{
		RegCloseKey(hKey);
		return;
	}
	RegCloseKey(hKey);


	if(!BaseServer.ListenStart())
	{
		KillTimer(2);
		MessageBox("Unable to start server.","Error",MB_OK | MB_ICONERROR);
		EndDialog(0);
		return;
	}
	ShowInfoBar();

	//StartLive();
	bDisableCallback = false;
}

void CRMSServerDlg::OnSave() 
{
	if(BaseServer.GetRecordState())
	{
		BaseServer.SetRecordState(FALSE);
//		SetDlgItemText(IDSAVE,"Record");
		BaseServer.CloseRecordDlg();
	}
	else
	{
		BaseServer.SetRecordState(TRUE);
//		SetDlgItemText(IDSAVE,"Stop");
		BaseServer.CloseRecordDlg();
		if(!BaseServer.OpenRecordDlg(this))
		{
			TRACE0("Unable to create status window");
			return;
		}
	}
}

void CRMSServerDlg::SetAudioStatus(STATUS nStatus)
{
	switch(nStatus)
	{
	case AUDIO_STATUS_DISABLE:
//		m_strAudioStatus = "Audio: Disabled";
		//SetDlgItemText(IDSOUND, "Turn Audio On");
		m_bAudio = FALSE;
		break;
	case AUDIO_STATUS_ACTIVE:
		m_bAudio = TRUE;
//		m_strAudioStatus = "Audio: Enabled";
		//SetDlgItemText(IDSOUND, "Turn Audio Off");
		break;
	}
	UpdateData(FALSE);
}

void CRMSServerDlg::SetVideoStatus(STATUS nStatus)
{
	switch(nStatus)
	{
	case VIDEO_STATUS_DISABLE:
//		m_strVideoStatus = "Video: Disabled";
		m_bVideo = FALSE;
		break;
	case VIDEO_STATUS_ACTIVE:
		m_bVideo = TRUE;
//		m_strVideoStatus = "Video: Enabled";
		break;
	}
_log(strtime()<<"Damn that frog("<<m_bVideo<<")!\n");
    BaseServer.ClientEnableNoVideo(255, !m_bVideo);
	UpdateData(FALSE);
}

void CRMSServerDlg::OnClose() 
{
	BeginWaitCursor();  // or AfxGetApp()->DoWaitCursor(1)
	// TODO: Add your message handler code here and/or call default
	KillTimer(0);
	KillTimer(1);
	KillTimer(2);
	KillTimer(3);
#ifdef _NET_VC_
	KillTimer(4);
#endif //def _NET_VC_

	bDisableCallback = true;

	BaseServer.Close();

	// done in Base server
	//DeleteCriticalSection(pCriticalData);
	//DeleteCriticalSection(pCriticalAudio);

//	WSACleanup();
#ifdef _CYCLIC_BUFFER_
	BaseServer.DeleteOldFiles();
#endif	
	//CMegaDialog::OnClose();
    EndWaitCursor();    // or AfxGetApp()->DoWaitCursor(-1)
	//CMegaDialog::DestroyWindow();
	EndDialog(0);

}
void CRMSServerDlg::OnIDCMinimize()  //charith 21-05-2015
{
	this->ShowWindow(SW_MINIMIZE);
}
void CRMSServerDlg::OnExit() 
{
	// TODO: Add your control notification handler code here
	OnClose();	
}

void CRMSServerDlg::OnDestroy()
{
#ifdef _NET_VC_
	if(WaitForSingleObject(m_hMutex, 5000) != WAIT_TIMEOUT)
	{
		WinPlace wp;
		wp.Save(this, ENCODER_REGISTRY_KEY, m_addr);
		ReleaseMutex(m_hMutex);
	}
#endif //def _NET_VC_

#ifdef _J707_ //#J7070021, #J7070022
	if (SaveLowMode() != 0)
	{
		MessageBox("I—¹Žž‚ÌLowƒ‚[ƒh‚Ì•Û‘¶‚ÅƒGƒ‰[‚ª”­¶‚µ‚Ü‚µ‚½B’l‚Í•Û‘¶‚³‚ê‚Ä‚¢‚È‚¢‰Â”\«‚ª‚ ‚è‚Ü‚·B","Warning",MB_OK | MB_ICONWARNING);
	}
	SaveEncoderParam();
#endif

	CMegaDialog::OnDestroy();
}

void CRMSServerDlg::OnPassword() 
{
	CPasswordDlg dlg;
	if(dlg.DoModal() == IDOK)
	{
		BaseServer.SetPassword(static_cast<LPCTSTR>(dlg.m_strPassword));
		BaseServer.SavePassword();
	}
}

void CRMSServerDlg::OnHelp() 
{
	if((int)(ShellExecute(NULL,NULL,"SEEGuide.pdf",NULL,NULL,SW_SHOW))<=32)
	{
		MessageBox("Unable to open help file. SEEGuide.pdf","Warning",MB_OK|MB_ICONWARNING);
	}
}

LRESULT CRMSServerDlg::OnCall(WPARAM wparam, LPARAM lparam) 
{
	if(((wparam == NULL) || (*((TCHAR*)wparam) == 0)) && (lparam != NULL))
	{
		*((int*)lparam) = m_bEnableBroadcast ? TAG_BROADCAST : TAG_GOODFORMAT;
		return 1;
	}

	// restore window
	this->ShowWindow(SW_SHOWNORMAL);

	// TODO: Add your control notification handler code here
	CString Caller = (LPSTR)wparam;

	if(m_bEnableBroadcast && (lparam != NULL) && (*((int*)lparam) == 0))
	{
		*((int*)lparam) = TAG_BROADCAST;
		return 1;
	}

	TCHAR site[100], str1[100], str2[100], str3[100];
	TCHAR TStr[100], IPStr[100], PWStr[100];
	int IDNum;

	_stscanf((LPCTSTR)Caller, "%s %s %s %s %i %s %s %s %s %s %s %s %s",
			 site, str1, str2, str3, &IDNum, PWStr, IPStr, TStr, TStr, TStr, TStr, TStr, TStr);

	CString title;
	title = site;
	title += _T(" ");
	title += str1;
	title += _T(" ");
	title += str2;
	title += _T(" ");
	title += str3;

	CInCall dlg(this, title, IPStr);

	if(dlg.DoModal() == IDOK)
	{
		if(lparam != NULL)
			*((int*)lparam) = TAG_GOODFORMAT;

		WPARAM Wip = inet_addr(IPStr);
		Call_Ok = 0;
#ifdef _J707_ // merge fom VC-X:#103R20016
		CString IPs = m_host.getAllHomeIPs();
		if (!strcmp(IPStr, "127.0.0.1") || (IPs.Find(IPStr) != -1)){
			Call_Ok = 1;
		}
#else
		::SendMessage(HWND_BROADCAST, RegisterWindowMessage("STREAM_BOX_MESSAGE"), Wip, IDNum);
#endif
		Sleep(100);
		BOOL Shell = (Call_Ok==0);

		// wake up camera if necessary
		StartLive();

		// TODO: Add your control notification handler code here
		TCHAR appName[_MAX_PATH];
		::GetModuleFileName(NULL, appName, _MAX_PATH);
#ifdef _NET_VC_
		_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\NVC.exe"));
#elif defined VC70
		_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\VC70.exe"));
#else
		_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\VC10.exe"));
#endif

		CString params = _T(" call ") + Caller;

		if(Shell)
			ShellExecute(0, _T("open"), appName, params, _T(""), SW_SHOWNORMAL);

        if(dlg.m_AddCaller)
		{
            bool AddressPresent = false;

			FILE* f = NULL;
			CString hp = getHomePath();
			if(hp.IsEmpty())
			{
				f = _tfopen(_T("live_cameras.txt"), _T("rb+"));
				if(!f)
				{
					//hp = _T("c:"); // default
					hp = _T(".");
					saveHomePath(hp);
				}
			}

			if(!f)
			{
				hp += _T("\\live_cameras.txt");
				f = _tfopen(hp, _T("rb+"));
			}

            if(f)
			{
                // check if address is present in the addressbook
                int id, tmp;

                while(1)
				{
                    _tcscpy(site, _T("none"));
                    _ftscanf(f, _T("%s %s %s %s %i %s %s %i %i %i %i %i %i"),
							 site, TStr, TStr, TStr, &id, str1, str2,
							 &tmp, &tmp, &tmp, &tmp, &tmp, &tmp);
                    if(_tcscmp(site, _T("none")))
					{
                        if(id != IDNum) continue;
                        if(_tcscmp(str1, PWStr)) continue;
                        if(_tcscmp(str2, IPStr)) continue;
                        AddressPresent=true;
                    }
					break;
                }
                
            }
            else
			{
				CString hp = getHomePath();
				hp += _T("\\live_cameras.txt");
				f = _tfopen(hp, _T("wb"));
			}

            if(!AddressPresent)
			{
                fseek(f, 0, SEEK_END);
                _ftprintf(f, _T("%s\n"), LPCTSTR(Caller));
            }

            fclose(f);

        }
	}
	else
	{
		if(lparam != NULL)
			*((int*)lparam) = TAG_BADFORMAT;
	}

	return 1;
}

void CRMSServerDlg::OnVC10()
{
	CallViewer(_T(""));
}

void CRMSServerDlg::CallViewer(LPCTSTR params)
{
	// start Live if neccessary
	StartLive();

	TCHAR appName[_MAX_PATH];
	::GetModuleFileName(NULL, appName, _MAX_PATH);
#ifdef _NET_VC_

#ifndef _VC_J7_
	_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\NVC.exe"));
#else

#ifdef _HCP_
	LPCTSTR MyAppName = ::AfxGetAppName();
	if (stricmp(MyAppName, "VC-J7EncoderNP") == 0) {
	    _tcscpy(_tcsrchr(appName, _T('\\')), _T("\\VC-J7NP.exe"));
	}
	else {
		_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\VC-J7cp.exe"));
	}
#else
	_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\VC-J7.exe"));
#endif

#endif

#elif defined VC70
	_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\VC70.exe"));
#else
	_tcscpy(_tcsrchr(appName, _T('\\')), _T("\\VC10.exe"));
#endif

	if((int)ShellExecute(0, _T("open"), appName, params, _T(""), SW_SHOWNORMAL) <= 32)
#ifdef _NET_VC_

#ifndef _VC_J7_
		MessageBox(_T("Cannot start NetVC Viewer. Please reinstall the application."));
#else

#ifdef _HCP_
		MessageBox(_T("Cannot start VC-J7cp Viewer. Please reinstall the application."));
#else
		MessageBox(_T("Cannot start VC-J7 Viewer. Please reinstall the application."));
#endif

#endif

#elif defined VC70
		MessageBox(_T("Cannot start VC70 Viewer. Please reinstall the application."));
#else
		MessageBox(_T("Cannot start VC10 Viewer. Please reinstall the application."));
#endif
}

void CRMSServerDlg::OnDblclkClients() 
{
	// TODO: Add your control notification handler code here
	CString ip;
	m_ClientsList.GetText(m_ClientsList.GetCurSel(), ip);
	CString addr = BaseServer.GetClientAddress(ip);
	if( !addr.IsEmpty() )
		addr = _T("call ") + addr;

	CallViewer(addr);
}

void CRMSServerDlg::OnSelchangeClients() 
{
	// TODO: Add your control notification handler code here
	
}

BOOL CRMSServerDlg::PreTranslateMessage(MSG* pMsg) 
{
	 if (pMsg->message == WM_KEYDOWN) {
		if (pMsg->wParam == VK_ESCAPE) {
			return TRUE;
		}
	 }
	 return CMegaDialog::PreTranslateMessage(pMsg);
}

void CRMSServerDlg::OnSound() 
{
	m_bAudio=!m_bAudio;
	UpdateFeedStatus();
}


void CRMSServerDlg::OnVideo() 
{
	m_bVideo=!m_bVideo;
    _log("krevedko: "<<m_bVideo<<"\n");
	UpdateFeedStatus();
#ifdef _NET_VC_
	if(m_bVideo)
	{
		KillTimer(4);
		if(g_hNoVideoEnabled) SetEvent(g_hNoVideoEnabled);
	}
	else
	{
		SetTimer(4, 2000, NULL);
	}
#endif //def _NET_VC_
}

void CRMSServerDlg::OnSleep() 
{
	// TODO: Add your control notification handler code here
_log("sleepy\n"<<"\n");
	if (SleepMode == 0) 
	{
		m_bAudio=FALSE;
		m_bVideo=FALSE;
	}
	else
	{
		m_bAudio=m_AudioDevicePresent;
		m_bVideo=m_VideoDevicePresent;
	}
	UpdateFeedStatus();
}

// updates status of preview window, enable/disable video and sound, buttons
void CRMSServerDlg::UpdateFeedStatus()
{
	if (FALSE == m_bVideo) 
	{
		GetDlgItem(IDC_PREVIEW)->ShowWindow(SW_HIDE);// disable preview
		m_bVideo = TRUE;		// Enable  update
		SetCustomImage();		// Update  with custom image
		m_bVideo = FALSE;		// Disable update

		SetVideoStatus(VIDEO_STATUS_DISABLE);
		m_VideoBtn.SetCheck(MBS_UNCHECK);
		// disable video
		capPVR_SetVideoStatus(FALSE);
	}
	else
	{
		SetVideoStatus(VIDEO_STATUS_ACTIVE);
		m_VideoBtn.SetCheck(MBS_CHECK);

		// enable capture
		if(bWasSetStillImage)
		{
			bWasSetStillImage = FALSE;
			capPVR_SetVideoStatus(TRUE);
		}
		Sleep(100);
		GetDlgItem(IDC_PREVIEW)->ShowWindow(SW_SHOW);// enable preview
		// enable video
		capPVR_SetVideoStatus(TRUE);
	}

	if (m_bAudio==FALSE) 
	{
		SetAudioStatus(AUDIO_STATUS_DISABLE);
		m_AudioBtn.SetCheck(MBS_UNCHECK);
		capPVR_SetAudioStatus(FALSE);
	}
	else
	{
		SetAudioStatus(AUDIO_STATUS_ACTIVE);
		m_AudioBtn.SetCheck(MBS_CHECK);
		capPVR_SetAudioStatus(TRUE);
	}

#ifndef _NET_VC_
	if ( (m_bVideo==FALSE) && (m_bAudio ==FALSE) ) 
	{
//		GetDlgItem(IDC_SLEEP)->SetWindowText("Wake");
		SleepMode=1;
		m_SleepBtn.SetCheck(MBS_CHECK);
	}
	else
	{
		SleepMode=0;
		m_SleepBtn.SetCheck(MBS_UNCHECK);
//		GetDlgItem(IDC_SLEEP)->SetWindowText("Sleep");
	}
#endif //ndef _NET_VC_
}

void CRMSServerDlg::StartLive()
{
	int r=capPVR_Start();
_log("StartLive: "<<r<<"\n");


	bDisableCallback = false;
}

void CRMSServerDlg::OnMouseMove(UINT nFlags, CPoint point) 
{
	//New Dialog UI Dragable DoerIT2015/5/21-> charith
	if(m_Dragable == TRUE)
	{
		CRect rc;
		GetWindowRect(&rc);
		m_moveCursorPos.x = (rc.left + rc.right) / 2;
		m_moveCursorPos.y = rc.top + 10;

		rc.MoveToX(rc.left + (point.x - m_moveOffset.x)); 
		rc.MoveToY(rc.top + (point.y - m_moveOffset.y)); 

		MoveWindow(&rc);
	}

	m_bMove = TRUE;
	CMegaDialog::OnMouseMove(nFlags, point);
}

void CRMSServerDlg::SetCustomImage()
{
	if (*BaseServer.GetDataPtr_TypeVideo(0) == TAG_RMSVIDEO_v01) {

		int video=m_bVideo;
//		m_bVideo=1;
_log("SetCustomImage!\n");
		bWasSetStillImage = TRUE;

		LPBITMAPINFOHEADER  lp;
		// set custom image -------------->>>>>>>><<-----------
		if (pSleepBitmapDataCompressed) {    
	//        lp=(LPBITMAPINFOHEADER)(pSleepBitmapData+sizeof(BITMAPFILEHEADER));
			Process(pSleepBitmapDataCompressed,sizeSleepCompressed,1);
	//	    SetStillImage(((BYTE*)lp)+(lp->biSize),4);
		}else{
    		HRSRC hInfo=FindResource(::AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_SB_BLUE),RT_BITMAP);
			HGLOBAL h=LoadResource(::AfxGetInstanceHandle(),hInfo);
			int size = SizeofResource(::AfxGetInstanceHandle(),hInfo);
			lp=(LPBITMAPINFOHEADER) LockResource(h);
			SetStillImage(((BYTE*)lp)+(lp->biSize),4);
			UnlockResource(h);
		}
		m_bVideo=video;
	}
}
void CRMSServerDlg::StopLive()
{
	// disable video caputure
	capPVR_Stop();
	Sleep(2000);
	SetCustomImage();
	bDisableCallback = true;
}


void CRMSServerDlg::DisableVideoButtons()
{
	CWnd *pWnd = 0;

//	m_strVideoStatus = "Video: audio-only device";
	
	// disable video on/off button
	m_VideoBtn.EnableWindow(FALSE);

#ifdef _GUI2008_
	//#J7070016: add condition "if" and add "SettingsMenu.EnableMenuItem()" to CRMServerDlg::EnableSettingsMenu()
	if(SettingsMenu)
	{
      SettingsMenu.EnableMenuItem(IDM_VIDEOSOURCE, MF_BYCOMMAND | MF_GRAYED);
	}
#endif

	// disable Select Video Source

#ifdef _NET_VC_

#ifndef _GUI2008_
	m_btnVideoSource.EnableWindow(FALSE);
#endif

#else //def _NET_VC_

	pWnd = GetDlgItem(IDSELECT);
	if(pWnd)
	{
		pWnd->EnableWindow(FALSE);
	}

#endif //def _NET_VC_
	m_bVideo=FALSE;	

}

LRESULT CRMSServerDlg::OnChangeServerParams(WPARAM wParam, LPARAM lParam)
{
	int nIP = wParam;
	int nPort = lParam;

	// process new port & new IP
	String strIP;
//	m_host.IPStringByNumber(strIP, nIP);
	IPArr arr;
	m_host.GetIPArr(arr);
	int n = 0;
	for(IPArr::const_iterator it = arr.begin(); it != arr.end(); it++, n++)
	{
		String str = (*it).second;
		if(n == nIP)
		{
			strIP.assign(str);
			break;
		}
	}

	// check if we need to restart whole server
	if((0 != strIP.compare(m_strIP)) || (nPort != m_nPort)) 
	{
		m_nPort = nPort;
		m_strIP = strIP.c_str();
		UpdateServer(m_strIP, m_nPort);
	}

	/*
    if (*BaseServer.GetDataPtr_TypeVideo(0)==TAG_RMSVIDEO_v02) {
        if (dlg->m_rb320==0)
            InitOutput(false);
    }
    else {
        if (dlg->m_rb640==0) {
            InitOutput(true);
           // InitOutput(true);
        }
    }
	*/

	StartLive();

	return 0;
}

LRESULT CRMSServerDlg::OnChangeCyclicBuffer(WPARAM wParam, LPARAM lParam)
{
	int nCycle = wParam;

	// process new cycle buffer size
#ifdef _CYCLIC_BUFFER_
	LONG lnRes;
	HKEY hKey;
	DWORD dwDisp;
	DWORD value;

	BaseServer.SetRecordCycle(nCycle);
	BaseServer.SignalDeleteOldFiles();

	lnRes = RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,KEY_ALL_ACCESS,&hKey);
	if(ERROR_SUCCESS != lnRes)
	{
		lnRes = RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,NULL,
			REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisp);
		if(ERROR_SUCCESS != lnRes)
		{
			RegCloseKey(hKey);
			return -1;
		}
	}

	value = (DWORD)(nCycle);
	lnRes = RegSetValueEx(hKey,"Cycle",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	RegCloseKey(hKey);
#endif

	return 0;
}

LRESULT CRMSServerDlg::OnChangeHomePath(WPARAM wParam, LPARAM lParam)
{
	saveHomePath((LPCTSTR)wParam);
	return 0;
}

LRESULT CRMSServerDlg::OnChangePassword(WPARAM wParam, LPARAM lParam)
{
	BaseServer.SetPassword((const char*) wParam);
	BaseServer.SavePassword();

	return 0;
}

LRESULT CRMSServerDlg::OnChangeBitrate(WPARAM wParam, LPARAM lParam)
{
	int nBitrate = wParam;
	bDisableCallback = true;
	StopLive();

_log("Will change bitrate to "<<nBitrate<<"\n");

	LONG lnRes;
	HKEY hKey;
	DWORD dwDisp;
	DWORD value;

	LOGRUS_reqbitrate = ((double)(nBitrate * 30)) / 1024.0;

	lnRes = RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,KEY_ALL_ACCESS,&hKey);
	if(ERROR_SUCCESS != lnRes)
	{
		lnRes = RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,NULL,
			REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisp);
		if(ERROR_SUCCESS != lnRes)
		{
			RegCloseKey(hKey);
			return -1;
		}
	}
	value = (DWORD)(nBitrate);
	lnRes = RegSetValueEx(hKey,"Bit rate",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	if(ERROR_SUCCESS != lnRes)
	{
		RegCloseKey(hKey);
		return -1;
	}

	RegCloseKey(hKey);

	StartLive();
	bDisableCallback = false;

	return 0;
}

LRESULT CRMSServerDlg::OnChangeFPS(WPARAM wParam, LPARAM lParam)
{
	int nFPS = wParam;
	StopLive();

_log("Will change FPS to "<<nFPS<<"\n");

	LONG lnRes;
	HKEY hKey;
	DWORD dwDisp;
	DWORD value;

	CRMSServerDlg* dlg = (CRMSServerDlg*)AfxGetMainWnd();

	capPVR_SetFrameRate(nFPS);
	m_nCurrentFPS = nFPS;

	lnRes = RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,KEY_ALL_ACCESS,&hKey);
	if(ERROR_SUCCESS != lnRes)
	{
		lnRes = RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,NULL,
			REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisp);
		if(ERROR_SUCCESS != lnRes)
		{
			RegCloseKey(hKey);
			return -1;
		}
	}

	value = nFPS;

	lnRes = RegSetValueEx(hKey,"Frame rate",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	if(ERROR_SUCCESS != lnRes)
	{
		RegCloseKey(hKey);
		return -1;
	}

	RegCloseKey(hKey);
_log("starting live with fps = "<<nFPS << "\n");
    StartLive();

	return 0;
}

int CRMSServerDlg::ChangeBitsAndFps(int bitsperframe, int fps)
{
    bDisableCallback = true;
	StopLive();
_log("Will change FPS to "<<nFPS<<"\n");
	
// === param update ===
	capPVR_SetFrameRate(fps);
	m_nCurrentFPS = fps;
    LOGRUS_reqbitrate = ((double)(bitsperframe * 30)) / 1024.0;

// === registry update ===
    HKEY hKey; DWORD dwDisp, value; LONG lnRes;
	lnRes = RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,KEY_ALL_ACCESS,&hKey);
	if(ERROR_SUCCESS != lnRes)
	{
		lnRes = RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,NULL,
			REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisp);
		if(ERROR_SUCCESS != lnRes)
		{
			RegCloseKey(hKey);
			return -1;
		}
	}
	value = fps;
	lnRes = RegSetValueEx(hKey,"Frame rate",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	if(ERROR_SUCCESS != lnRes)
	{
		RegCloseKey(hKey);
		return -1;
	}
    value = bitsperframe;
	lnRes = RegSetValueEx(hKey,"Bit rate",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	if(ERROR_SUCCESS != lnRes)
	{
		RegCloseKey(hKey);
		return -1;
	}
	RegCloseKey(hKey);


    StartLive();
    bDisableCallback = false;
	return 0;
}


LRESULT CRMSServerDlg::OnChangeSize(WPARAM wParam, LPARAM lParam)
{
	BOOL bSize640x480 = (BOOL)wParam;

	StopLive();
	LockWindowUpdate();

	if (*BaseServer.GetDataPtr_TypeVideo(0) == TAG_RMSVIDEO_v02) 
	{
		if(!bSize640x480)	
			InitOutput(false);
	}
	else
	{
		if(bSize640x480)	
			InitOutput(true);
	}

	bDisableCallback = false;
	//	SetCustomImage();
	bDisableCallback = true;

	StartLive();
	UnlockWindowUpdate();

	return 0;
}

// ýòî ü@ðàáîò÷èê Eú@E broadcast
// âûçûâàåòE E úüæàòèþ EúCæàòèþ Eú@E
// m_bEnableBroadcast - áóEâñEÿ EðåEûLE, EEçûâàåò ðàçðåøåí áðûüäêàñEèëEûDE(true/false)

void CRMSServerDlg::OnCast()
{
#ifndef _GUI2008_
	m_btnConf.SetCheck(MBS_UNCHECK);
#endif
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	pSysMenu->CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_CHECKED);
    pSysMenu->CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_UNCHECKED);

	m_bEnableBroadcast = true;
	//BaseServer.DeleteAllClients();
	BaseServer.SetMode_NewPassword(-1);
	REGISTRY_SaveInt(KEY_CAST_CONF, 1);
}

void CRMSServerDlg::OnConf()
{
#ifndef _GUI2008_
	m_btnCast.SetCheck(MBS_UNCHECK);
#endif
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	pSysMenu->CheckMenuItem(IDM_CAST, MF_BYCOMMAND | MF_UNCHECKED);
    pSysMenu->CheckMenuItem(IDM_CONF, MF_BYCOMMAND | MF_CHECKED);

	m_bEnableBroadcast = false;
	//BaseServer.DeleteAllClients();
	BaseServer.SetMode_NewPassword(-1);
	REGISTRY_SaveInt(KEY_CAST_CONF, 0);
}
#ifdef _GUI2008_
void CRMSServerDlg::OnHi()
{
	m_btnLow.SetCheck(MBS_UNCHECK);
	int oldFR = m_spDlg.GetFrameRate();
    int oldBR = m_spDlg.GetBitRate();
    m_spDlg.PresetBitRate(presetBitsHi);
    m_spDlg.PresetFrameRate(presetFpsHi);

	if(presetFpsHi != oldFR)
//		OnChangeFPS((WPARAM)newFR, 0L);
      ChangeBitsAndFps(presetBitsHi, presetFpsHi);

}
void CRMSServerDlg::OnLow()
{
    m_btnHi.SetCheck(MBS_UNCHECK);
	int oldFR = m_spDlg.GetFrameRate();
    int oldBR = m_spDlg.GetBitRate();
    m_spDlg.PresetBitRate(presetBitsLow);
    m_spDlg.PresetFrameRate(presetFpsLow);

	if(presetFpsLow != oldFR)
//		OnChangeFPS((WPARAM)newFR, 0L);
      ChangeBitsAndFps(presetBitsLow,presetFpsLow);

}
#endif


// WPARAM,LPARAM are necessary for ON_MESSAGE, otherwise stack will be corrupted
LRESULT CRMSServerDlg::User_Message(WPARAM,LPARAM)
{

	Call_Ok = 1;
	return 1;
}

void CRMSServerDlg::initHomePath()
{
	TCHAR buf[256];
	m_homePath = _T("");
	if(REGISTRY_LoadString(KEY_HOME_PATH, buf, sizeof(buf)))
	{
		m_homePath = buf;
	}
	else
	{
		//saveHomePath(_T("c:"));
		saveHomePath(_T("."));
	}
}

LPCTSTR CRMSServerDlg::getHomePath()
{
	return m_homePath;
}

void CRMSServerDlg::saveHomePath(LPCTSTR home)
{
	m_homePath = home;
	REGISTRY_SaveString(KEY_HOME_PATH, home);
}
#ifdef _IPR_
LRESULT CRMSServerDlg::OnRegistIP(WPARAM wParam, LPARAM lParam)
{

	if (!BaseServer.m_bEnableIpr)
	{
		#ifdef _DEBUG
			//MessageBox("OnRegistIP - Ignore WM_APP+10 because missing -ipr option.", "VC-J7 Encoder:OnUnregistIP", MB_OK);
		#endif
		return TRUE;
	}
	EnterCriticalSection(&BaseServer.m_IprCritical);
	char ip[128];
	char netmask[128];
	char netid[128];
	ULONG subnetmask = (0xffffffff >> (32-lParam)) << (32-lParam);
	BYTE b_subnet[4];
	b_subnet[0] = subnetmask >> 24;
	b_subnet[1] = subnetmask >> 16;
	b_subnet[2] = subnetmask >> 8;
	b_subnet[3] = subnetmask;

	BYTE in_ip[4];
	in_ip[0] = wParam&255;
	in_ip[1] = (wParam>>8)&255;
	in_ip[2] = (wParam>>16)&255;
	in_ip[3] = (wParam>>24)&255;
	sprintf(ip, "%d.%d.%d.%d", in_ip[0], in_ip[1], in_ip[2], in_ip[3]);
	sprintf(netmask, "%d", lParam);
	sprintf(netid,  "%d.%d.%d.%d", in_ip[0]&b_subnet[0], in_ip[1]&b_subnet[1], in_ip[2]&b_subnet[2], in_ip[3]&b_subnet[3]);
	BaseServer.m_registIp[ip].m_Netmask[netmask].m_ip = ip;
	BaseServer.m_registIp[ip].m_Netmask[netmask].m_netmask = lParam;
	BaseServer.m_registIp[ip].m_Netmask[netmask].m_netid = netid;

    LeaveCriticalSection(&BaseServer.m_IprCritical);	

	return TRUE;
}
LRESULT CRMSServerDlg::OnUnregistIP(WPARAM wParam, LPARAM lParam)
{
	if (!BaseServer.m_bEnableIpr)
	{
		#ifdef _DEBUG
			//MessageBox("OnUnregistIP - Ignore WM_APP+10 because missing -ipr option.", "VC-J7 Encoder:OnUnregistIP", MB_OK);
		#endif
		return TRUE;
	}
	EnterCriticalSection(&BaseServer.m_IprCritical);

	char ip[128];
	char netmask[128];
	sprintf(ip, "%d.%d.%d.%d", wParam&255, (wParam>>8)&255, (wParam>>16)&255, (wParam>>24)&255);
	sprintf(netmask, "%d", lParam);

	// Search IP/netmask
	map<CString, CAllowIP> * m_pRegistIp;
	m_pRegistIp = &BaseServer.m_registIp;
	map<CString, CAllowIP>::iterator pIp = m_pRegistIp->find(ip);

	if (pIp != m_pRegistIp->end())
	{
		map<CString, CNetmask> *  m_pNetmask;
		m_pNetmask = &BaseServer.m_registIp[ip].m_Netmask;
		map<CString, CNetmask>::iterator pNet = m_pNetmask->find(netmask);

		if (pNet != m_pNetmask->end())
		{
			m_pNetmask->erase(pNet);
		}
		if (m_pNetmask->empty())
		{
			m_pRegistIp->erase(pIp);
		}
	}

	LeaveCriticalSection(&BaseServer.m_IprCritical);	
	return TRUE;
}

#endif // _IPR_

#ifdef _J707_
//
// #J7070021
LRESULT CRMSServerDlg::SaveLowMode()
{
	int nFPS = 1;

_log("Will save FPS to "<<nFPS<<"\n");

	LONG lnRes;
	HKEY hKey;
	DWORD dwDisp;
	DWORD value;

	lnRes = RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,KEY_ALL_ACCESS,&hKey);
	if(ERROR_SUCCESS != lnRes)
	{
		lnRes = RegCreateKeyEx(HKEY_CURRENT_USER,"Software\\Streambox Everywhere\\Settings",0,NULL,
			REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisp);
		if(ERROR_SUCCESS != lnRes)
		{
			RegCloseKey(hKey);
			return -1;
		}
	}

	value = nFPS;

	lnRes = RegSetValueEx(hKey,"Frame rate",NULL,REG_DWORD,(BYTE*)&(value),sizeof(DWORD));
	if(ERROR_SUCCESS != lnRes)
	{
		RegCloseKey(hKey);
		return -1;
	}

	RegCloseKey(hKey);
_log("Saved FPS = "<<nFPS << "\n");
	return 0;
}
//
// #J7070022
LRESULT CRMSServerDlg::SaveEncoderParam()
{
	LRESULT hr;
	//
	// Save Video ON/OFF to Registory
    hr = REGISTRY_SaveInt(KEY_VIDEO, (int)m_bVideo);
	if (hr != TRUE)
	{
		MessageBox("I—¹Žž‚ÌƒrƒfƒI ƒ‚[ƒh‚Ì•Û‘¶‚ÅƒGƒ‰[‚ª”­¶‚µ‚Ü‚µ‚½B’l‚Í•Û‘¶‚³‚ê‚Ä‚¢‚È‚¢‰Â”\«‚ª‚ ‚è‚Ü‚·B","Warning",MB_OK | MB_ICONWARNING);
	}
	//
	// Save Audio ON/OFF to Registory
	hr = REGISTRY_SaveInt(KEY_AUDIO, (int)m_bAudio);
    if (hr != TRUE)
	{
		MessageBox("I—¹Žž‚ÌƒI[ƒfƒBƒI ƒ‚[ƒh‚Ì•Û‘¶‚ÅƒGƒ‰[‚ª”­¶‚µ‚Ü‚µ‚½B’l‚Í•Û‘¶‚³‚ê‚Ä‚¢‚È‚¢‰Â”\«‚ª‚ ‚è‚Ü‚·B","Warning",MB_OK | MB_ICONWARNING);
	}
	return S_OK;

}
LRESULT CRMSServerDlg::LoadEncoderParam()
{
	int result;
	wchar_t msg[200];
	char modeStatus[4];
	//
	// Load Video mode from Registry
	result = -2;
    result = REGISTRY_LoadInt(KEY_VIDEO, result);
	if (result != -2)
	{
		m_bVideo = (bool)result;
	}
	else
	{
		if (m_bVideo)
		{
			sprintf(modeStatus, "%s", (const char*)"ON");
		}
		else
		{
			sprintf(modeStatus, "%s", (const char*)"OFF");
		}
		sprintf((char*)msg, 
			"ƒrƒfƒI ƒ‚[ƒh‚Í•Û‘¶‚³‚ê‚½Ž–‚ª–³‚¢‚©A‚Ü‚½‚Í‘O‰ñ•Û‘¶‚µ‚½’l‚ÌŽæ“¾Žž‚ÉƒGƒ‰[‚ª”­¶‚µ‚Ü‚µ‚½BƒrƒfƒI‚ÍŒ»Ý‚Ì’lu%sv‚Å“®ì‚µ‚Ü‚·B",  
			(const char*)modeStatus);
		MessageBox((LPCSTR)msg,"Warning",MB_OK | MB_ICONWARNING);
	}
	//
	// Load Audio mode from Registry
	result = -2;
    result = REGISTRY_LoadInt(KEY_AUDIO, result);
	if (result != -2)
	{
		m_bAudio = (bool)result;
	}
	else
	{
		if (m_bAudio)
		{
			sprintf(modeStatus, "%s", (const char*)"ON");
		}
		else
		{
			sprintf(modeStatus, "%s", (const char*)"OFF");
		}
		sprintf((char*)msg,  
			"ƒI[ƒfƒBƒI ƒ‚[ƒh‚Í•Û‘¶‚³‚ê‚½Ž–‚ª–³‚¢‚©A‚Ü‚½‚Í‘O‰ñ•Û‘¶‚µ‚½’l‚ÌŽæ“¾Žž‚ÉƒGƒ‰[‚ª”­¶‚µ‚Ü‚µ‚½BƒI[ƒfƒBƒI‚ÍŒ»Ý‚Ì’lu%sv‚Å“®ì‚µ‚Ü‚·B", 
			(const char*)modeStatus);
		MessageBox((LPCSTR)msg,"Warning",MB_OK | MB_ICONWARNING);
	}
	return S_OK;
}
#endif // _J707_